es6.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545
  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. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8129. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function (request) {
  9097. if (request && request.status > 400) {
  9098. if (onError) {
  9099. onError(request);
  9100. }
  9101. }
  9102. else {
  9103. if (!aborted) {
  9104. requestFile();
  9105. }
  9106. }
  9107. };
  9108. var loadFromIndexedDB = function () {
  9109. // TODO: database needs to support aborting and should return a IFileRequest
  9110. if (aborted) {
  9111. return;
  9112. }
  9113. if (database) {
  9114. database.loadFileFromDB(url, function (data) {
  9115. if (!aborted) {
  9116. onSuccess(data);
  9117. }
  9118. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9119. }, onProgress ? function (event) {
  9120. if (!aborted) {
  9121. onProgress(event);
  9122. }
  9123. } : undefined, noIndexedDB_1, useArrayBuffer);
  9124. }
  9125. };
  9126. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9127. }
  9128. else {
  9129. requestFile();
  9130. }
  9131. return fileRequest;
  9132. };
  9133. /**
  9134. * Load a script (identified by an url). When the url returns, the
  9135. * content of this file is added into a new script element, attached to the DOM (body element)
  9136. */
  9137. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9138. var head = document.getElementsByTagName('head')[0];
  9139. var script = document.createElement('script');
  9140. script.type = 'text/javascript';
  9141. script.src = scriptUrl;
  9142. script.onload = function () {
  9143. if (onSuccess) {
  9144. onSuccess();
  9145. }
  9146. };
  9147. script.onerror = function (e) {
  9148. if (onError) {
  9149. onError("Unable to load script '" + scriptUrl + "'", e);
  9150. }
  9151. };
  9152. head.appendChild(script);
  9153. };
  9154. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9155. var reader = new FileReader();
  9156. var request = {
  9157. onCompleteObservable: new BABYLON.Observable(),
  9158. abort: function () { return reader.abort(); },
  9159. };
  9160. reader.onloadend = function (e) {
  9161. request.onCompleteObservable.notifyObservers(request);
  9162. };
  9163. reader.onload = function (e) {
  9164. //target doesn't have result from ts 1.3
  9165. callback(e.target['result']);
  9166. };
  9167. reader.onprogress = progressCallback;
  9168. reader.readAsDataURL(fileToLoad);
  9169. return request;
  9170. };
  9171. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9172. var reader = new FileReader();
  9173. var request = {
  9174. onCompleteObservable: new BABYLON.Observable(),
  9175. abort: function () { return reader.abort(); },
  9176. };
  9177. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9178. reader.onerror = function (e) {
  9179. Tools.Log("Error while reading file: " + fileToLoad.name);
  9180. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9181. };
  9182. reader.onload = function (e) {
  9183. //target doesn't have result from ts 1.3
  9184. callback(e.target['result']);
  9185. };
  9186. if (progressCallBack) {
  9187. reader.onprogress = progressCallBack;
  9188. }
  9189. if (!useArrayBuffer) {
  9190. // Asynchronous read
  9191. reader.readAsText(fileToLoad);
  9192. }
  9193. else {
  9194. reader.readAsArrayBuffer(fileToLoad);
  9195. }
  9196. return request;
  9197. };
  9198. //returns a downloadable url to a file content.
  9199. Tools.FileAsURL = function (content) {
  9200. var fileBlob = new Blob([content]);
  9201. var url = window.URL || window.webkitURL;
  9202. var link = url.createObjectURL(fileBlob);
  9203. return link;
  9204. };
  9205. // Misc.
  9206. Tools.Format = function (value, decimals) {
  9207. if (decimals === void 0) { decimals = 2; }
  9208. return value.toFixed(decimals);
  9209. };
  9210. Tools.CheckExtends = function (v, min, max) {
  9211. if (v.x < min.x)
  9212. min.x = v.x;
  9213. if (v.y < min.y)
  9214. min.y = v.y;
  9215. if (v.z < min.z)
  9216. min.z = v.z;
  9217. if (v.x > max.x)
  9218. max.x = v.x;
  9219. if (v.y > max.y)
  9220. max.y = v.y;
  9221. if (v.z > max.z)
  9222. max.z = v.z;
  9223. };
  9224. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9225. for (var prop in source) {
  9226. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9227. continue;
  9228. }
  9229. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9230. continue;
  9231. }
  9232. var sourceValue = source[prop];
  9233. var typeOfSourceValue = typeof sourceValue;
  9234. if (typeOfSourceValue === "function") {
  9235. continue;
  9236. }
  9237. try {
  9238. if (typeOfSourceValue === "object") {
  9239. if (sourceValue instanceof Array) {
  9240. destination[prop] = [];
  9241. if (sourceValue.length > 0) {
  9242. if (typeof sourceValue[0] == "object") {
  9243. for (var index = 0; index < sourceValue.length; index++) {
  9244. var clonedValue = cloneValue(sourceValue[index], destination);
  9245. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9246. destination[prop].push(clonedValue);
  9247. }
  9248. }
  9249. }
  9250. else {
  9251. destination[prop] = sourceValue.slice(0);
  9252. }
  9253. }
  9254. }
  9255. else {
  9256. destination[prop] = cloneValue(sourceValue, destination);
  9257. }
  9258. }
  9259. else {
  9260. destination[prop] = sourceValue;
  9261. }
  9262. }
  9263. catch (e) {
  9264. // Just ignore error (it could be because of a read-only property)
  9265. }
  9266. }
  9267. };
  9268. Tools.IsEmpty = function (obj) {
  9269. for (var i in obj) {
  9270. if (obj.hasOwnProperty(i)) {
  9271. return false;
  9272. }
  9273. }
  9274. return true;
  9275. };
  9276. Tools.RegisterTopRootEvents = function (events) {
  9277. for (var index = 0; index < events.length; index++) {
  9278. var event = events[index];
  9279. window.addEventListener(event.name, event.handler, false);
  9280. try {
  9281. if (window.parent) {
  9282. window.parent.addEventListener(event.name, event.handler, false);
  9283. }
  9284. }
  9285. catch (e) {
  9286. // Silently fails...
  9287. }
  9288. }
  9289. };
  9290. Tools.UnregisterTopRootEvents = function (events) {
  9291. for (var index = 0; index < events.length; index++) {
  9292. var event = events[index];
  9293. window.removeEventListener(event.name, event.handler);
  9294. try {
  9295. if (window.parent) {
  9296. window.parent.removeEventListener(event.name, event.handler);
  9297. }
  9298. }
  9299. catch (e) {
  9300. // Silently fails...
  9301. }
  9302. }
  9303. };
  9304. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9305. if (mimeType === void 0) { mimeType = "image/png"; }
  9306. // Read the contents of the framebuffer
  9307. var numberOfChannelsByLine = width * 4;
  9308. var halfHeight = height / 2;
  9309. //Reading datas from WebGL
  9310. var data = engine.readPixels(0, 0, width, height);
  9311. //To flip image on Y axis.
  9312. for (var i = 0; i < halfHeight; i++) {
  9313. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9314. var currentCell = j + i * numberOfChannelsByLine;
  9315. var targetLine = height - i - 1;
  9316. var targetCell = j + targetLine * numberOfChannelsByLine;
  9317. var temp = data[currentCell];
  9318. data[currentCell] = data[targetCell];
  9319. data[targetCell] = temp;
  9320. }
  9321. }
  9322. // Create a 2D canvas to store the result
  9323. if (!screenshotCanvas) {
  9324. screenshotCanvas = document.createElement('canvas');
  9325. }
  9326. screenshotCanvas.width = width;
  9327. screenshotCanvas.height = height;
  9328. var context = screenshotCanvas.getContext('2d');
  9329. if (context) {
  9330. // Copy the pixels to a 2D canvas
  9331. var imageData = context.createImageData(width, height);
  9332. var castData = (imageData.data);
  9333. castData.set(data);
  9334. context.putImageData(imageData, 0, 0);
  9335. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9336. }
  9337. };
  9338. /**
  9339. * Converts the canvas data to blob.
  9340. * This acts as a polyfill for browsers not supporting the to blob function.
  9341. * @param canvas Defines the canvas to extract the data from
  9342. * @param successCallback Defines the callback triggered once the data are available
  9343. * @param mimeType Defines the mime type of the result
  9344. */
  9345. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9346. if (mimeType === void 0) { mimeType = "image/png"; }
  9347. // We need HTMLCanvasElement.toBlob for HD screenshots
  9348. if (!canvas.toBlob) {
  9349. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9350. canvas.toBlob = function (callback, type, quality) {
  9351. var _this = this;
  9352. setTimeout(function () {
  9353. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9354. for (var i = 0; i < len; i++) {
  9355. arr[i] = binStr.charCodeAt(i);
  9356. }
  9357. callback(new Blob([arr]));
  9358. });
  9359. };
  9360. }
  9361. canvas.toBlob(function (blob) {
  9362. successCallback(blob);
  9363. }, mimeType);
  9364. };
  9365. /**
  9366. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9367. * @param successCallback Defines the callback triggered once the data are available
  9368. * @param mimeType Defines the mime type of the result
  9369. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9370. */
  9371. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9372. if (mimeType === void 0) { mimeType = "image/png"; }
  9373. if (successCallback) {
  9374. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9375. successCallback(base64Image);
  9376. }
  9377. else {
  9378. this.ToBlob(screenshotCanvas, function (blob) {
  9379. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9380. if (("download" in document.createElement("a"))) {
  9381. if (!fileName) {
  9382. var date = new Date();
  9383. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9384. fileName = "screenshot_" + stringDate + ".png";
  9385. }
  9386. Tools.Download(blob, fileName);
  9387. }
  9388. else {
  9389. var url = URL.createObjectURL(blob);
  9390. var newWindow = window.open("");
  9391. if (!newWindow)
  9392. return;
  9393. var img = newWindow.document.createElement("img");
  9394. img.onload = function () {
  9395. // no longer need to read the blob so it's revoked
  9396. URL.revokeObjectURL(url);
  9397. };
  9398. img.src = url;
  9399. newWindow.document.body.appendChild(img);
  9400. }
  9401. }, mimeType);
  9402. }
  9403. };
  9404. /**
  9405. * Downloads a blob in the browser
  9406. * @param blob defines the blob to download
  9407. * @param fileName defines the name of the downloaded file
  9408. */
  9409. Tools.Download = function (blob, fileName) {
  9410. var url = window.URL.createObjectURL(blob);
  9411. var a = document.createElement("a");
  9412. document.body.appendChild(a);
  9413. a.style.display = "none";
  9414. a.href = url;
  9415. a.download = fileName;
  9416. a.addEventListener("click", function () {
  9417. if (a.parentElement) {
  9418. a.parentElement.removeChild(a);
  9419. }
  9420. });
  9421. a.click();
  9422. window.URL.revokeObjectURL(url);
  9423. };
  9424. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9425. if (mimeType === void 0) { mimeType = "image/png"; }
  9426. var width;
  9427. var height;
  9428. // If a precision value is specified
  9429. if (size.precision) {
  9430. width = Math.round(engine.getRenderWidth() * size.precision);
  9431. height = Math.round(width / engine.getAspectRatio(camera));
  9432. }
  9433. else if (size.width && size.height) {
  9434. width = size.width;
  9435. height = size.height;
  9436. }
  9437. //If passing only width, computing height to keep display canvas ratio.
  9438. else if (size.width && !size.height) {
  9439. width = size.width;
  9440. height = Math.round(width / engine.getAspectRatio(camera));
  9441. }
  9442. //If passing only height, computing width to keep display canvas ratio.
  9443. else if (size.height && !size.width) {
  9444. height = size.height;
  9445. width = Math.round(height * engine.getAspectRatio(camera));
  9446. }
  9447. //Assuming here that "size" parameter is a number
  9448. else if (!isNaN(size)) {
  9449. height = size;
  9450. width = size;
  9451. }
  9452. else {
  9453. Tools.Error("Invalid 'size' parameter !");
  9454. return;
  9455. }
  9456. if (!screenshotCanvas) {
  9457. screenshotCanvas = document.createElement('canvas');
  9458. }
  9459. screenshotCanvas.width = width;
  9460. screenshotCanvas.height = height;
  9461. var renderContext = screenshotCanvas.getContext("2d");
  9462. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9463. var newWidth = width;
  9464. var newHeight = newWidth / ratio;
  9465. if (newHeight > height) {
  9466. newHeight = height;
  9467. newWidth = newHeight * ratio;
  9468. }
  9469. var offsetX = Math.max(0, width - newWidth) / 2;
  9470. var offsetY = Math.max(0, height - newHeight) / 2;
  9471. var renderingCanvas = engine.getRenderingCanvas();
  9472. if (renderContext && renderingCanvas) {
  9473. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9474. }
  9475. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9476. };
  9477. /**
  9478. * Generates an image screenshot from the specified camera.
  9479. *
  9480. * @param engine The engine to use for rendering
  9481. * @param camera The camera to use for rendering
  9482. * @param size This parameter can be set to a single number or to an object with the
  9483. * following (optional) properties: precision, width, height. If a single number is passed,
  9484. * it will be used for both width and height. If an object is passed, the screenshot size
  9485. * will be derived from the parameters. The precision property is a multiplier allowing
  9486. * rendering at a higher or lower resolution.
  9487. * @param successCallback The callback receives a single parameter which contains the
  9488. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9489. * src parameter of an <img> to display it.
  9490. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9491. * Check your browser for supported MIME types.
  9492. * @param samples Texture samples (default: 1)
  9493. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9494. * @param fileName A name for for the downloaded file.
  9495. * @constructor
  9496. */
  9497. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9498. if (mimeType === void 0) { mimeType = "image/png"; }
  9499. if (samples === void 0) { samples = 1; }
  9500. if (antialiasing === void 0) { antialiasing = false; }
  9501. var width;
  9502. var height;
  9503. //If a precision value is specified
  9504. if (size.precision) {
  9505. width = Math.round(engine.getRenderWidth() * size.precision);
  9506. height = Math.round(width / engine.getAspectRatio(camera));
  9507. size = { width: width, height: height };
  9508. }
  9509. else if (size.width && size.height) {
  9510. width = size.width;
  9511. height = size.height;
  9512. }
  9513. //If passing only width, computing height to keep display canvas ratio.
  9514. else if (size.width && !size.height) {
  9515. width = size.width;
  9516. height = Math.round(width / engine.getAspectRatio(camera));
  9517. size = { width: width, height: height };
  9518. }
  9519. //If passing only height, computing width to keep display canvas ratio.
  9520. else if (size.height && !size.width) {
  9521. height = size.height;
  9522. width = Math.round(height * engine.getAspectRatio(camera));
  9523. size = { width: width, height: height };
  9524. }
  9525. //Assuming here that "size" parameter is a number
  9526. else if (!isNaN(size)) {
  9527. height = size;
  9528. width = size;
  9529. }
  9530. else {
  9531. Tools.Error("Invalid 'size' parameter !");
  9532. return;
  9533. }
  9534. var scene = camera.getScene();
  9535. var previousCamera = null;
  9536. if (scene.activeCamera !== camera) {
  9537. previousCamera = scene.activeCamera;
  9538. scene.activeCamera = camera;
  9539. }
  9540. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9541. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9542. texture.renderList = null;
  9543. texture.samples = samples;
  9544. if (antialiasing) {
  9545. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9546. }
  9547. texture.onAfterRenderObservable.add(function () {
  9548. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9549. });
  9550. scene.incrementRenderId();
  9551. scene.resetCachedMaterial();
  9552. texture.render(true);
  9553. texture.dispose();
  9554. if (previousCamera) {
  9555. scene.activeCamera = previousCamera;
  9556. }
  9557. camera.getProjectionMatrix(true); // Force cache refresh;
  9558. };
  9559. // XHR response validator for local file scenario
  9560. Tools.ValidateXHRData = function (xhr, dataType) {
  9561. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9562. if (dataType === void 0) { dataType = 7; }
  9563. try {
  9564. if (dataType & 1) {
  9565. if (xhr.responseText && xhr.responseText.length > 0) {
  9566. return true;
  9567. }
  9568. else if (dataType === 1) {
  9569. return false;
  9570. }
  9571. }
  9572. if (dataType & 2) {
  9573. // Check header width and height since there is no "TGA" magic number
  9574. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9575. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9576. return true;
  9577. }
  9578. else if (dataType === 2) {
  9579. return false;
  9580. }
  9581. }
  9582. if (dataType & 4) {
  9583. // Check for the "DDS" magic number
  9584. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9585. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9586. return true;
  9587. }
  9588. else {
  9589. return false;
  9590. }
  9591. }
  9592. }
  9593. catch (e) {
  9594. // Global protection
  9595. }
  9596. return false;
  9597. };
  9598. /**
  9599. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9600. * Be aware Math.random() could cause collisions, but:
  9601. * "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"
  9602. */
  9603. Tools.RandomId = function () {
  9604. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9605. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9606. return v.toString(16);
  9607. });
  9608. };
  9609. /**
  9610. * Test if the given uri is a base64 string.
  9611. * @param uri The uri to test
  9612. * @return True if the uri is a base64 string or false otherwise.
  9613. */
  9614. Tools.IsBase64 = function (uri) {
  9615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9616. };
  9617. /**
  9618. * Decode the given base64 uri.
  9619. * @param uri The uri to decode
  9620. * @return The decoded base64 data.
  9621. */
  9622. Tools.DecodeBase64 = function (uri) {
  9623. var decodedString = atob(uri.split(",")[1]);
  9624. var bufferLength = decodedString.length;
  9625. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9626. for (var i = 0; i < bufferLength; i++) {
  9627. bufferView[i] = decodedString.charCodeAt(i);
  9628. }
  9629. return bufferView.buffer;
  9630. };
  9631. Object.defineProperty(Tools, "NoneLogLevel", {
  9632. get: function () {
  9633. return Tools._NoneLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "MessageLogLevel", {
  9639. get: function () {
  9640. return Tools._MessageLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "WarningLogLevel", {
  9646. get: function () {
  9647. return Tools._WarningLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "ErrorLogLevel", {
  9653. get: function () {
  9654. return Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "AllLogLevel", {
  9660. get: function () {
  9661. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Tools._AddLogEntry = function (entry) {
  9667. Tools._LogCache = entry + Tools._LogCache;
  9668. if (Tools.OnNewCacheEntry) {
  9669. Tools.OnNewCacheEntry(entry);
  9670. }
  9671. };
  9672. Tools._FormatMessage = function (message) {
  9673. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9674. var date = new Date();
  9675. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9676. };
  9677. Tools._LogDisabled = function (message) {
  9678. // nothing to do
  9679. };
  9680. Tools._LogEnabled = function (message) {
  9681. var formattedMessage = Tools._FormatMessage(message);
  9682. console.log("BJS - " + formattedMessage);
  9683. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9684. Tools._AddLogEntry(entry);
  9685. };
  9686. Tools._WarnDisabled = function (message) {
  9687. // nothing to do
  9688. };
  9689. Tools._WarnEnabled = function (message) {
  9690. var formattedMessage = Tools._FormatMessage(message);
  9691. console.warn("BJS - " + formattedMessage);
  9692. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9693. Tools._AddLogEntry(entry);
  9694. };
  9695. Tools._ErrorDisabled = function (message) {
  9696. // nothing to do
  9697. };
  9698. Tools._ErrorEnabled = function (message) {
  9699. Tools.errorsCount++;
  9700. var formattedMessage = Tools._FormatMessage(message);
  9701. console.error("BJS - " + formattedMessage);
  9702. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9703. Tools._AddLogEntry(entry);
  9704. };
  9705. Object.defineProperty(Tools, "LogCache", {
  9706. get: function () {
  9707. return Tools._LogCache;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Tools.ClearLogCache = function () {
  9713. Tools._LogCache = "";
  9714. Tools.errorsCount = 0;
  9715. };
  9716. Object.defineProperty(Tools, "LogLevels", {
  9717. set: function (level) {
  9718. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9719. Tools.Log = Tools._LogEnabled;
  9720. }
  9721. else {
  9722. Tools.Log = Tools._LogDisabled;
  9723. }
  9724. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9725. Tools.Warn = Tools._WarnEnabled;
  9726. }
  9727. else {
  9728. Tools.Warn = Tools._WarnDisabled;
  9729. }
  9730. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9731. Tools.Error = Tools._ErrorEnabled;
  9732. }
  9733. else {
  9734. Tools.Error = Tools._ErrorDisabled;
  9735. }
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Tools.IsWindowObjectExist = function () {
  9741. return (typeof window) !== "undefined";
  9742. };
  9743. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceNoneLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceUserMarkLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9758. get: function () {
  9759. return Tools._PerformanceConsoleLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9765. set: function (level) {
  9766. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9767. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9768. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9769. return;
  9770. }
  9771. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9772. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9773. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9774. return;
  9775. }
  9776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9777. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9783. };
  9784. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9785. };
  9786. Tools._StartUserMark = function (counterName, condition) {
  9787. if (condition === void 0) { condition = true; }
  9788. if (!Tools._performance) {
  9789. if (!Tools.IsWindowObjectExist()) {
  9790. return;
  9791. }
  9792. Tools._performance = window.performance;
  9793. }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-Begin");
  9798. };
  9799. Tools._EndUserMark = function (counterName, condition) {
  9800. if (condition === void 0) { condition = true; }
  9801. if (!condition || !Tools._performance.mark) {
  9802. return;
  9803. }
  9804. Tools._performance.mark(counterName + "-End");
  9805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9806. };
  9807. Tools._StartPerformanceConsole = function (counterName, condition) {
  9808. if (condition === void 0) { condition = true; }
  9809. if (!condition) {
  9810. return;
  9811. }
  9812. Tools._StartUserMark(counterName, condition);
  9813. if (console.time) {
  9814. console.time(counterName);
  9815. }
  9816. };
  9817. Tools._EndPerformanceConsole = function (counterName, condition) {
  9818. if (condition === void 0) { condition = true; }
  9819. if (!condition) {
  9820. return;
  9821. }
  9822. Tools._EndUserMark(counterName, condition);
  9823. if (console.time) {
  9824. console.timeEnd(counterName);
  9825. }
  9826. };
  9827. Object.defineProperty(Tools, "Now", {
  9828. get: function () {
  9829. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9830. return window.performance.now();
  9831. }
  9832. return Date.now();
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. /**
  9838. * This method will return the name of the class used to create the instance of the given object.
  9839. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9840. * @param object the object to get the class name from
  9841. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9842. */
  9843. Tools.GetClassName = function (object, isType) {
  9844. if (isType === void 0) { isType = false; }
  9845. var name = null;
  9846. if (!isType && object.getClassName) {
  9847. name = object.getClassName();
  9848. }
  9849. else {
  9850. if (object instanceof Object) {
  9851. var classObj = isType ? object : Object.getPrototypeOf(object);
  9852. name = classObj.constructor["__bjsclassName__"];
  9853. }
  9854. if (!name) {
  9855. name = typeof object;
  9856. }
  9857. }
  9858. return name;
  9859. };
  9860. Tools.First = function (array, predicate) {
  9861. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9862. var el = array_1[_i];
  9863. if (predicate(el)) {
  9864. return el;
  9865. }
  9866. }
  9867. return null;
  9868. };
  9869. /**
  9870. * This method will return the name of the full name of the class, including its owning module (if any).
  9871. * 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).
  9872. * @param object the object to get the class name from
  9873. * @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.
  9874. */
  9875. Tools.getFullClassName = function (object, isType) {
  9876. if (isType === void 0) { isType = false; }
  9877. var className = null;
  9878. var moduleName = null;
  9879. if (!isType && object.getClassName) {
  9880. className = object.getClassName();
  9881. }
  9882. else {
  9883. if (object instanceof Object) {
  9884. var classObj = isType ? object : Object.getPrototypeOf(object);
  9885. className = classObj.constructor["__bjsclassName__"];
  9886. moduleName = classObj.constructor["__bjsmoduleName__"];
  9887. }
  9888. if (!className) {
  9889. className = typeof object;
  9890. }
  9891. }
  9892. if (!className) {
  9893. return null;
  9894. }
  9895. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9896. };
  9897. /**
  9898. * 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.
  9899. * @param array
  9900. */
  9901. Tools.arrayOrStringFeeder = function (array) {
  9902. return function (index) {
  9903. if (index >= array.length) {
  9904. return null;
  9905. }
  9906. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9907. if (val && val.getHashCode) {
  9908. val = val.getHashCode();
  9909. }
  9910. if (typeof val === "string") {
  9911. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9912. }
  9913. return val;
  9914. };
  9915. };
  9916. /**
  9917. * Compute the hashCode of a stream of number
  9918. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9919. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9920. * @return the hash code computed
  9921. */
  9922. Tools.hashCodeFromStream = function (feeder) {
  9923. // Based from here: http://stackoverflow.com/a/7616484/802124
  9924. var hash = 0;
  9925. var index = 0;
  9926. var chr = feeder(index++);
  9927. while (chr != null) {
  9928. hash = ((hash << 5) - hash) + chr;
  9929. hash |= 0; // Convert to 32bit integer
  9930. chr = feeder(index++);
  9931. }
  9932. return hash;
  9933. };
  9934. /**
  9935. * Returns a promise that resolves after the given amount of time.
  9936. * @param delay Number of milliseconds to delay
  9937. * @returns Promise that resolves after the given amount of time
  9938. */
  9939. Tools.DelayAsync = function (delay) {
  9940. return new Promise(function (resolve) {
  9941. setTimeout(function () {
  9942. resolve();
  9943. }, delay);
  9944. });
  9945. };
  9946. /**
  9947. * Gets the current gradient from an array of IValueGradient
  9948. * @param ratio defines the current ratio to get
  9949. * @param gradients defines the array of IValueGradient
  9950. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9951. */
  9952. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9953. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9954. var currentGradient = gradients[gradientIndex];
  9955. var nextGradient = gradients[gradientIndex + 1];
  9956. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9957. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9958. updateFunc(currentGradient, nextGradient, scale);
  9959. }
  9960. }
  9961. };
  9962. Tools.BaseUrl = "";
  9963. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9964. /**
  9965. * Default behaviour for cors in the application.
  9966. * It can be a string if the expected behavior is identical in the entire app.
  9967. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9968. */
  9969. Tools.CorsBehavior = "anonymous";
  9970. Tools.UseFallbackTexture = true;
  9971. /**
  9972. * Use this object to register external classes like custom textures or material
  9973. * to allow the laoders to instantiate them
  9974. */
  9975. Tools.RegisteredExternalClasses = {};
  9976. // Used in case of a texture loading problem
  9977. 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";
  9978. Tools._tmpFloatArray = new Float32Array(1);
  9979. Tools.PreprocessUrl = function (url) {
  9980. return url;
  9981. };
  9982. // Logs
  9983. Tools._NoneLogLevel = 0;
  9984. Tools._MessageLogLevel = 1;
  9985. Tools._WarningLogLevel = 2;
  9986. Tools._ErrorLogLevel = 4;
  9987. Tools._LogCache = "";
  9988. Tools.errorsCount = 0;
  9989. Tools.Log = Tools._LogEnabled;
  9990. Tools.Warn = Tools._WarnEnabled;
  9991. Tools.Error = Tools._ErrorEnabled;
  9992. // Performances
  9993. Tools._PerformanceNoneLogLevel = 0;
  9994. Tools._PerformanceUserMarkLogLevel = 1;
  9995. Tools._PerformanceConsoleLogLevel = 2;
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9998. return Tools;
  9999. }());
  10000. BABYLON.Tools = Tools;
  10001. /**
  10002. * This class is used to track a performance counter which is number based.
  10003. * The user has access to many properties which give statistics of different nature
  10004. *
  10005. * The implementer can track two kinds of Performance Counter: time and count
  10006. * 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.
  10007. * 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.
  10008. */
  10009. var PerfCounter = /** @class */ (function () {
  10010. function PerfCounter() {
  10011. this._startMonitoringTime = 0;
  10012. this._min = 0;
  10013. this._max = 0;
  10014. this._average = 0;
  10015. this._lastSecAverage = 0;
  10016. this._current = 0;
  10017. this._totalValueCount = 0;
  10018. this._totalAccumulated = 0;
  10019. this._lastSecAccumulated = 0;
  10020. this._lastSecTime = 0;
  10021. this._lastSecValueCount = 0;
  10022. }
  10023. Object.defineProperty(PerfCounter.prototype, "min", {
  10024. /**
  10025. * Returns the smallest value ever
  10026. */
  10027. get: function () {
  10028. return this._min;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(PerfCounter.prototype, "max", {
  10034. /**
  10035. * Returns the biggest value ever
  10036. */
  10037. get: function () {
  10038. return this._max;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(PerfCounter.prototype, "average", {
  10044. /**
  10045. * Returns the average value since the performance counter is running
  10046. */
  10047. get: function () {
  10048. return this._average;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10054. /**
  10055. * Returns the average value of the last second the counter was monitored
  10056. */
  10057. get: function () {
  10058. return this._lastSecAverage;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(PerfCounter.prototype, "current", {
  10064. /**
  10065. * Returns the current value
  10066. */
  10067. get: function () {
  10068. return this._current;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "total", {
  10074. get: function () {
  10075. return this._totalAccumulated;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(PerfCounter.prototype, "count", {
  10081. get: function () {
  10082. return this._totalValueCount;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. /**
  10088. * Call this method to start monitoring a new frame.
  10089. * 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.
  10090. */
  10091. PerfCounter.prototype.fetchNewFrame = function () {
  10092. this._totalValueCount++;
  10093. this._current = 0;
  10094. this._lastSecValueCount++;
  10095. };
  10096. /**
  10097. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10098. * @param newCount the count value to add to the monitored count
  10099. * @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.
  10100. */
  10101. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10102. if (!PerfCounter.Enabled) {
  10103. return;
  10104. }
  10105. this._current += newCount;
  10106. if (fetchResult) {
  10107. this._fetchResult();
  10108. }
  10109. };
  10110. /**
  10111. * Start monitoring this performance counter
  10112. */
  10113. PerfCounter.prototype.beginMonitoring = function () {
  10114. if (!PerfCounter.Enabled) {
  10115. return;
  10116. }
  10117. this._startMonitoringTime = Tools.Now;
  10118. };
  10119. /**
  10120. * Compute the time lapsed since the previous beginMonitoring() call.
  10121. * @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
  10122. */
  10123. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10124. if (newFrame === void 0) { newFrame = true; }
  10125. if (!PerfCounter.Enabled) {
  10126. return;
  10127. }
  10128. if (newFrame) {
  10129. this.fetchNewFrame();
  10130. }
  10131. var currentTime = Tools.Now;
  10132. this._current = currentTime - this._startMonitoringTime;
  10133. if (newFrame) {
  10134. this._fetchResult();
  10135. }
  10136. };
  10137. PerfCounter.prototype._fetchResult = function () {
  10138. this._totalAccumulated += this._current;
  10139. this._lastSecAccumulated += this._current;
  10140. // Min/Max update
  10141. this._min = Math.min(this._min, this._current);
  10142. this._max = Math.max(this._max, this._current);
  10143. this._average = this._totalAccumulated / this._totalValueCount;
  10144. // Reset last sec?
  10145. var now = Tools.Now;
  10146. if ((now - this._lastSecTime) > 1000) {
  10147. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10148. this._lastSecTime = now;
  10149. this._lastSecAccumulated = 0;
  10150. this._lastSecValueCount = 0;
  10151. }
  10152. };
  10153. PerfCounter.Enabled = true;
  10154. return PerfCounter;
  10155. }());
  10156. BABYLON.PerfCounter = PerfCounter;
  10157. /**
  10158. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10159. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10160. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10161. * @param name The name of the class, case should be preserved
  10162. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10163. */
  10164. function className(name, module) {
  10165. return function (target) {
  10166. target["__bjsclassName__"] = name;
  10167. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10168. };
  10169. }
  10170. BABYLON.className = className;
  10171. /**
  10172. * An implementation of a loop for asynchronous functions.
  10173. */
  10174. var AsyncLoop = /** @class */ (function () {
  10175. /**
  10176. * Constroctor.
  10177. * @param iterations the number of iterations.
  10178. * @param _fn the function to run each iteration
  10179. * @param _successCallback the callback that will be called upon succesful execution
  10180. * @param offset starting offset.
  10181. */
  10182. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10183. if (offset === void 0) { offset = 0; }
  10184. this.iterations = iterations;
  10185. this._fn = _fn;
  10186. this._successCallback = _successCallback;
  10187. this.index = offset - 1;
  10188. this._done = false;
  10189. }
  10190. /**
  10191. * Execute the next iteration. Must be called after the last iteration was finished.
  10192. */
  10193. AsyncLoop.prototype.executeNext = function () {
  10194. if (!this._done) {
  10195. if (this.index + 1 < this.iterations) {
  10196. ++this.index;
  10197. this._fn(this);
  10198. }
  10199. else {
  10200. this.breakLoop();
  10201. }
  10202. }
  10203. };
  10204. /**
  10205. * Break the loop and run the success callback.
  10206. */
  10207. AsyncLoop.prototype.breakLoop = function () {
  10208. this._done = true;
  10209. this._successCallback();
  10210. };
  10211. /**
  10212. * Helper function
  10213. */
  10214. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10215. if (offset === void 0) { offset = 0; }
  10216. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10217. loop.executeNext();
  10218. return loop;
  10219. };
  10220. /**
  10221. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10222. * @param iterations total number of iterations
  10223. * @param syncedIterations number of synchronous iterations in each async iteration.
  10224. * @param fn the function to call each iteration.
  10225. * @param callback a success call back that will be called when iterating stops.
  10226. * @param breakFunction a break condition (optional)
  10227. * @param timeout timeout settings for the setTimeout function. default - 0.
  10228. * @constructor
  10229. */
  10230. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10231. if (timeout === void 0) { timeout = 0; }
  10232. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10233. if (breakFunction && breakFunction())
  10234. loop.breakLoop();
  10235. else {
  10236. setTimeout(function () {
  10237. for (var i = 0; i < syncedIterations; ++i) {
  10238. var iteration = (loop.index * syncedIterations) + i;
  10239. if (iteration >= iterations)
  10240. break;
  10241. fn(iteration);
  10242. if (breakFunction && breakFunction()) {
  10243. loop.breakLoop();
  10244. break;
  10245. }
  10246. }
  10247. loop.executeNext();
  10248. }, timeout);
  10249. }
  10250. }, callback);
  10251. };
  10252. return AsyncLoop;
  10253. }());
  10254. BABYLON.AsyncLoop = AsyncLoop;
  10255. })(BABYLON || (BABYLON = {}));
  10256. //# sourceMappingURL=babylon.tools.js.map
  10257. var BABYLON;
  10258. (function (BABYLON) {
  10259. var PromiseStates;
  10260. (function (PromiseStates) {
  10261. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10262. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10263. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10264. })(PromiseStates || (PromiseStates = {}));
  10265. var FulFillmentAgregator = /** @class */ (function () {
  10266. function FulFillmentAgregator() {
  10267. this.count = 0;
  10268. this.target = 0;
  10269. this.results = [];
  10270. }
  10271. return FulFillmentAgregator;
  10272. }());
  10273. var InternalPromise = /** @class */ (function () {
  10274. function InternalPromise(resolver) {
  10275. var _this = this;
  10276. this._state = PromiseStates.Pending;
  10277. this._children = new Array();
  10278. this._rejectWasConsumed = false;
  10279. if (!resolver) {
  10280. return;
  10281. }
  10282. try {
  10283. resolver(function (value) {
  10284. _this._resolve(value);
  10285. }, function (reason) {
  10286. _this._reject(reason);
  10287. });
  10288. }
  10289. catch (e) {
  10290. this._reject(e);
  10291. }
  10292. }
  10293. Object.defineProperty(InternalPromise.prototype, "_result", {
  10294. get: function () {
  10295. return this._resultValue;
  10296. },
  10297. set: function (value) {
  10298. this._resultValue = value;
  10299. if (this._parent && this._parent._result === undefined) {
  10300. this._parent._result = value;
  10301. }
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. InternalPromise.prototype.catch = function (onRejected) {
  10307. return this.then(undefined, onRejected);
  10308. };
  10309. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10310. var _this = this;
  10311. var newPromise = new InternalPromise();
  10312. newPromise._onFulfilled = onFulfilled;
  10313. newPromise._onRejected = onRejected;
  10314. // Composition
  10315. this._children.push(newPromise);
  10316. newPromise._parent = this;
  10317. if (this._state !== PromiseStates.Pending) {
  10318. BABYLON.Tools.SetImmediate(function () {
  10319. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10320. var returnedValue = newPromise._resolve(_this._result);
  10321. if (returnedValue !== undefined && returnedValue !== null) {
  10322. if (returnedValue._state !== undefined) {
  10323. var returnedPromise = returnedValue;
  10324. newPromise._children.push(returnedPromise);
  10325. returnedPromise._parent = newPromise;
  10326. newPromise = returnedPromise;
  10327. }
  10328. else {
  10329. newPromise._result = returnedValue;
  10330. }
  10331. }
  10332. }
  10333. else {
  10334. newPromise._reject(_this._reason);
  10335. }
  10336. });
  10337. }
  10338. return newPromise;
  10339. };
  10340. InternalPromise.prototype._moveChildren = function (children) {
  10341. var _this = this;
  10342. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10343. this._children.forEach(function (child) {
  10344. child._parent = _this;
  10345. });
  10346. if (this._state === PromiseStates.Fulfilled) {
  10347. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10348. var child = _b[_i];
  10349. child._resolve(this._result);
  10350. }
  10351. }
  10352. else if (this._state === PromiseStates.Rejected) {
  10353. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10354. var child = _d[_c];
  10355. child._reject(this._reason);
  10356. }
  10357. }
  10358. var _a;
  10359. };
  10360. InternalPromise.prototype._resolve = function (value) {
  10361. try {
  10362. this._state = PromiseStates.Fulfilled;
  10363. var returnedValue = null;
  10364. if (this._onFulfilled) {
  10365. returnedValue = this._onFulfilled(value);
  10366. }
  10367. if (returnedValue !== undefined && returnedValue !== null) {
  10368. if (returnedValue._state !== undefined) {
  10369. // Transmit children
  10370. var returnedPromise = returnedValue;
  10371. returnedPromise._parent = this;
  10372. returnedPromise._moveChildren(this._children);
  10373. value = returnedPromise._result;
  10374. }
  10375. else {
  10376. value = returnedValue;
  10377. }
  10378. }
  10379. this._result = value;
  10380. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10381. var child = _a[_i];
  10382. child._resolve(value);
  10383. }
  10384. this._children.length = 0;
  10385. delete this._onFulfilled;
  10386. delete this._onRejected;
  10387. }
  10388. catch (e) {
  10389. this._reject(e, true);
  10390. }
  10391. };
  10392. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10393. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10394. this._state = PromiseStates.Rejected;
  10395. this._reason = reason;
  10396. if (this._onRejected && !onLocalThrow) {
  10397. try {
  10398. this._onRejected(reason);
  10399. this._rejectWasConsumed = true;
  10400. }
  10401. catch (e) {
  10402. reason = e;
  10403. }
  10404. }
  10405. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10406. var child = _a[_i];
  10407. if (this._rejectWasConsumed) {
  10408. child._resolve(null);
  10409. }
  10410. else {
  10411. child._reject(reason);
  10412. }
  10413. }
  10414. this._children.length = 0;
  10415. delete this._onFulfilled;
  10416. delete this._onRejected;
  10417. };
  10418. InternalPromise.resolve = function (value) {
  10419. var newPromise = new InternalPromise();
  10420. newPromise._resolve(value);
  10421. return newPromise;
  10422. };
  10423. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10424. promise.then(function (value) {
  10425. agregator.results[index] = value;
  10426. agregator.count++;
  10427. if (agregator.count === agregator.target) {
  10428. agregator.rootPromise._resolve(agregator.results);
  10429. }
  10430. return null;
  10431. }, function (reason) {
  10432. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10433. agregator.rootPromise._reject(reason);
  10434. }
  10435. });
  10436. };
  10437. InternalPromise.all = function (promises) {
  10438. var newPromise = new InternalPromise();
  10439. var agregator = new FulFillmentAgregator();
  10440. agregator.target = promises.length;
  10441. agregator.rootPromise = newPromise;
  10442. if (promises.length) {
  10443. for (var index = 0; index < promises.length; index++) {
  10444. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10445. }
  10446. }
  10447. else {
  10448. newPromise._resolve([]);
  10449. }
  10450. return newPromise;
  10451. };
  10452. InternalPromise.race = function (promises) {
  10453. var newPromise = new InternalPromise();
  10454. if (promises.length) {
  10455. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10456. var promise = promises_1[_i];
  10457. promise.then(function (value) {
  10458. if (newPromise) {
  10459. newPromise._resolve(value);
  10460. newPromise = null;
  10461. }
  10462. return null;
  10463. }, function (reason) {
  10464. if (newPromise) {
  10465. newPromise._reject(reason);
  10466. newPromise = null;
  10467. }
  10468. });
  10469. }
  10470. }
  10471. return newPromise;
  10472. };
  10473. return InternalPromise;
  10474. }());
  10475. /**
  10476. * Helper class that provides a small promise polyfill
  10477. */
  10478. var PromisePolyfill = /** @class */ (function () {
  10479. function PromisePolyfill() {
  10480. }
  10481. /**
  10482. * Static function used to check if the polyfill is required
  10483. * If this is the case then the function will inject the polyfill to window.Promise
  10484. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10485. */
  10486. PromisePolyfill.Apply = function (force) {
  10487. if (force === void 0) { force = false; }
  10488. if (force || typeof Promise === 'undefined') {
  10489. var root = window;
  10490. root.Promise = InternalPromise;
  10491. }
  10492. };
  10493. return PromisePolyfill;
  10494. }());
  10495. BABYLON.PromisePolyfill = PromisePolyfill;
  10496. })(BABYLON || (BABYLON = {}));
  10497. //# sourceMappingURL=babylon.promise.js.map
  10498. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10499. var BABYLON;
  10500. (function (BABYLON) {
  10501. /**
  10502. * Helper class to push actions to a pool of workers.
  10503. */
  10504. var WorkerPool = /** @class */ (function () {
  10505. /**
  10506. * Constructor
  10507. * @param workers Array of workers to use for actions
  10508. */
  10509. function WorkerPool(workers) {
  10510. this._pendingActions = new Array();
  10511. this._workerInfos = workers.map(function (worker) { return ({
  10512. worker: worker,
  10513. active: false
  10514. }); });
  10515. }
  10516. /**
  10517. * Terminates all workers and clears any pending actions.
  10518. */
  10519. WorkerPool.prototype.dispose = function () {
  10520. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10521. var workerInfo = _a[_i];
  10522. workerInfo.worker.terminate();
  10523. }
  10524. delete this._workerInfos;
  10525. delete this._pendingActions;
  10526. };
  10527. /**
  10528. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10529. * pended until a worker has completed its action.
  10530. * @param action The action to perform. Call onComplete when the action is complete.
  10531. */
  10532. WorkerPool.prototype.push = function (action) {
  10533. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10534. var workerInfo = _a[_i];
  10535. if (!workerInfo.active) {
  10536. this._execute(workerInfo, action);
  10537. return;
  10538. }
  10539. }
  10540. this._pendingActions.push(action);
  10541. };
  10542. WorkerPool.prototype._execute = function (workerInfo, action) {
  10543. var _this = this;
  10544. workerInfo.active = true;
  10545. action(workerInfo.worker, function () {
  10546. workerInfo.active = false;
  10547. var nextAction = _this._pendingActions.shift();
  10548. if (nextAction) {
  10549. _this._execute(workerInfo, nextAction);
  10550. }
  10551. });
  10552. };
  10553. return WorkerPool;
  10554. }());
  10555. BABYLON.WorkerPool = WorkerPool;
  10556. })(BABYLON || (BABYLON = {}));
  10557. //# sourceMappingURL=babylon.workerPool.js.map
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. /**
  10561. * @hidden
  10562. **/
  10563. var _AlphaState = /** @class */ (function () {
  10564. /**
  10565. * Initializes the state.
  10566. */
  10567. function _AlphaState() {
  10568. this._isAlphaBlendDirty = false;
  10569. this._isBlendFunctionParametersDirty = false;
  10570. this._isBlendEquationParametersDirty = false;
  10571. this._isBlendConstantsDirty = false;
  10572. this._alphaBlend = false;
  10573. this._blendFunctionParameters = new Array(4);
  10574. this._blendEquationParameters = new Array(2);
  10575. this._blendConstants = new Array(4);
  10576. this.reset();
  10577. }
  10578. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10579. get: function () {
  10580. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10586. get: function () {
  10587. return this._alphaBlend;
  10588. },
  10589. set: function (value) {
  10590. if (this._alphaBlend === value) {
  10591. return;
  10592. }
  10593. this._alphaBlend = value;
  10594. this._isAlphaBlendDirty = true;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10600. if (this._blendConstants[0] === r &&
  10601. this._blendConstants[1] === g &&
  10602. this._blendConstants[2] === b &&
  10603. this._blendConstants[3] === a) {
  10604. return;
  10605. }
  10606. this._blendConstants[0] = r;
  10607. this._blendConstants[1] = g;
  10608. this._blendConstants[2] = b;
  10609. this._blendConstants[3] = a;
  10610. this._isBlendConstantsDirty = true;
  10611. };
  10612. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10613. if (this._blendFunctionParameters[0] === value0 &&
  10614. this._blendFunctionParameters[1] === value1 &&
  10615. this._blendFunctionParameters[2] === value2 &&
  10616. this._blendFunctionParameters[3] === value3) {
  10617. return;
  10618. }
  10619. this._blendFunctionParameters[0] = value0;
  10620. this._blendFunctionParameters[1] = value1;
  10621. this._blendFunctionParameters[2] = value2;
  10622. this._blendFunctionParameters[3] = value3;
  10623. this._isBlendFunctionParametersDirty = true;
  10624. };
  10625. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10626. if (this._blendEquationParameters[0] === rgb &&
  10627. this._blendEquationParameters[1] === alpha) {
  10628. return;
  10629. }
  10630. this._blendEquationParameters[0] = rgb;
  10631. this._blendEquationParameters[1] = alpha;
  10632. this._isBlendEquationParametersDirty = true;
  10633. };
  10634. _AlphaState.prototype.reset = function () {
  10635. this._alphaBlend = false;
  10636. this._blendFunctionParameters[0] = null;
  10637. this._blendFunctionParameters[1] = null;
  10638. this._blendFunctionParameters[2] = null;
  10639. this._blendFunctionParameters[3] = null;
  10640. this._blendEquationParameters[0] = null;
  10641. this._blendEquationParameters[1] = null;
  10642. this._blendConstants[0] = null;
  10643. this._blendConstants[1] = null;
  10644. this._blendConstants[2] = null;
  10645. this._blendConstants[3] = null;
  10646. this._isAlphaBlendDirty = true;
  10647. this._isBlendFunctionParametersDirty = false;
  10648. this._isBlendEquationParametersDirty = false;
  10649. this._isBlendConstantsDirty = false;
  10650. };
  10651. _AlphaState.prototype.apply = function (gl) {
  10652. if (!this.isDirty) {
  10653. return;
  10654. }
  10655. // Alpha blend
  10656. if (this._isAlphaBlendDirty) {
  10657. if (this._alphaBlend) {
  10658. gl.enable(gl.BLEND);
  10659. }
  10660. else {
  10661. gl.disable(gl.BLEND);
  10662. }
  10663. this._isAlphaBlendDirty = false;
  10664. }
  10665. // Alpha function
  10666. if (this._isBlendFunctionParametersDirty) {
  10667. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10668. this._isBlendFunctionParametersDirty = false;
  10669. }
  10670. // Alpha equation
  10671. if (this._isBlendEquationParametersDirty) {
  10672. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10673. this._isBlendEquationParametersDirty = false;
  10674. }
  10675. // Constants
  10676. if (this._isBlendConstantsDirty) {
  10677. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10678. this._isBlendConstantsDirty = false;
  10679. }
  10680. };
  10681. return _AlphaState;
  10682. }());
  10683. BABYLON._AlphaState = _AlphaState;
  10684. })(BABYLON || (BABYLON = {}));
  10685. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10686. var BABYLON;
  10687. (function (BABYLON) {
  10688. /**
  10689. * @hidden
  10690. **/
  10691. var _DepthCullingState = /** @class */ (function () {
  10692. /**
  10693. * Initializes the state.
  10694. */
  10695. function _DepthCullingState() {
  10696. this._isDepthTestDirty = false;
  10697. this._isDepthMaskDirty = false;
  10698. this._isDepthFuncDirty = false;
  10699. this._isCullFaceDirty = false;
  10700. this._isCullDirty = false;
  10701. this._isZOffsetDirty = false;
  10702. this._isFrontFaceDirty = false;
  10703. this.reset();
  10704. }
  10705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10706. get: function () {
  10707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10713. get: function () {
  10714. return this._zOffset;
  10715. },
  10716. set: function (value) {
  10717. if (this._zOffset === value) {
  10718. return;
  10719. }
  10720. this._zOffset = value;
  10721. this._isZOffsetDirty = true;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10727. get: function () {
  10728. return this._cullFace;
  10729. },
  10730. set: function (value) {
  10731. if (this._cullFace === value) {
  10732. return;
  10733. }
  10734. this._cullFace = value;
  10735. this._isCullFaceDirty = true;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10741. get: function () {
  10742. return this._cull;
  10743. },
  10744. set: function (value) {
  10745. if (this._cull === value) {
  10746. return;
  10747. }
  10748. this._cull = value;
  10749. this._isCullDirty = true;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10755. get: function () {
  10756. return this._depthFunc;
  10757. },
  10758. set: function (value) {
  10759. if (this._depthFunc === value) {
  10760. return;
  10761. }
  10762. this._depthFunc = value;
  10763. this._isDepthFuncDirty = true;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10769. get: function () {
  10770. return this._depthMask;
  10771. },
  10772. set: function (value) {
  10773. if (this._depthMask === value) {
  10774. return;
  10775. }
  10776. this._depthMask = value;
  10777. this._isDepthMaskDirty = true;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10783. get: function () {
  10784. return this._depthTest;
  10785. },
  10786. set: function (value) {
  10787. if (this._depthTest === value) {
  10788. return;
  10789. }
  10790. this._depthTest = value;
  10791. this._isDepthTestDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10797. get: function () {
  10798. return this._frontFace;
  10799. },
  10800. set: function (value) {
  10801. if (this._frontFace === value) {
  10802. return;
  10803. }
  10804. this._frontFace = value;
  10805. this._isFrontFaceDirty = true;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. _DepthCullingState.prototype.reset = function () {
  10811. this._depthMask = true;
  10812. this._depthTest = true;
  10813. this._depthFunc = null;
  10814. this._cullFace = null;
  10815. this._cull = null;
  10816. this._zOffset = 0;
  10817. this._frontFace = null;
  10818. this._isDepthTestDirty = true;
  10819. this._isDepthMaskDirty = true;
  10820. this._isDepthFuncDirty = false;
  10821. this._isCullFaceDirty = false;
  10822. this._isCullDirty = false;
  10823. this._isZOffsetDirty = false;
  10824. this._isFrontFaceDirty = false;
  10825. };
  10826. _DepthCullingState.prototype.apply = function (gl) {
  10827. if (!this.isDirty) {
  10828. return;
  10829. }
  10830. // Cull
  10831. if (this._isCullDirty) {
  10832. if (this.cull) {
  10833. gl.enable(gl.CULL_FACE);
  10834. }
  10835. else {
  10836. gl.disable(gl.CULL_FACE);
  10837. }
  10838. this._isCullDirty = false;
  10839. }
  10840. // Cull face
  10841. if (this._isCullFaceDirty) {
  10842. gl.cullFace(this.cullFace);
  10843. this._isCullFaceDirty = false;
  10844. }
  10845. // Depth mask
  10846. if (this._isDepthMaskDirty) {
  10847. gl.depthMask(this.depthMask);
  10848. this._isDepthMaskDirty = false;
  10849. }
  10850. // Depth test
  10851. if (this._isDepthTestDirty) {
  10852. if (this.depthTest) {
  10853. gl.enable(gl.DEPTH_TEST);
  10854. }
  10855. else {
  10856. gl.disable(gl.DEPTH_TEST);
  10857. }
  10858. this._isDepthTestDirty = false;
  10859. }
  10860. // Depth func
  10861. if (this._isDepthFuncDirty) {
  10862. gl.depthFunc(this.depthFunc);
  10863. this._isDepthFuncDirty = false;
  10864. }
  10865. // zOffset
  10866. if (this._isZOffsetDirty) {
  10867. if (this.zOffset) {
  10868. gl.enable(gl.POLYGON_OFFSET_FILL);
  10869. gl.polygonOffset(this.zOffset, 0);
  10870. }
  10871. else {
  10872. gl.disable(gl.POLYGON_OFFSET_FILL);
  10873. }
  10874. this._isZOffsetDirty = false;
  10875. }
  10876. // Front face
  10877. if (this._isFrontFaceDirty) {
  10878. gl.frontFace(this.frontFace);
  10879. this._isFrontFaceDirty = false;
  10880. }
  10881. };
  10882. return _DepthCullingState;
  10883. }());
  10884. BABYLON._DepthCullingState = _DepthCullingState;
  10885. })(BABYLON || (BABYLON = {}));
  10886. //# sourceMappingURL=babylon.depthCullingState.js.map
  10887. var BABYLON;
  10888. (function (BABYLON) {
  10889. /**
  10890. * @hidden
  10891. **/
  10892. var _StencilState = /** @class */ (function () {
  10893. function _StencilState() {
  10894. this._isStencilTestDirty = false;
  10895. this._isStencilMaskDirty = false;
  10896. this._isStencilFuncDirty = false;
  10897. this._isStencilOpDirty = false;
  10898. this.reset();
  10899. }
  10900. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10901. get: function () {
  10902. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10908. get: function () {
  10909. return this._stencilFunc;
  10910. },
  10911. set: function (value) {
  10912. if (this._stencilFunc === value) {
  10913. return;
  10914. }
  10915. this._stencilFunc = value;
  10916. this._isStencilFuncDirty = true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10922. get: function () {
  10923. return this._stencilFuncRef;
  10924. },
  10925. set: function (value) {
  10926. if (this._stencilFuncRef === value) {
  10927. return;
  10928. }
  10929. this._stencilFuncRef = value;
  10930. this._isStencilFuncDirty = true;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10936. get: function () {
  10937. return this._stencilFuncMask;
  10938. },
  10939. set: function (value) {
  10940. if (this._stencilFuncMask === value) {
  10941. return;
  10942. }
  10943. this._stencilFuncMask = value;
  10944. this._isStencilFuncDirty = true;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10950. get: function () {
  10951. return this._stencilOpStencilFail;
  10952. },
  10953. set: function (value) {
  10954. if (this._stencilOpStencilFail === value) {
  10955. return;
  10956. }
  10957. this._stencilOpStencilFail = value;
  10958. this._isStencilOpDirty = true;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10964. get: function () {
  10965. return this._stencilOpDepthFail;
  10966. },
  10967. set: function (value) {
  10968. if (this._stencilOpDepthFail === value) {
  10969. return;
  10970. }
  10971. this._stencilOpDepthFail = value;
  10972. this._isStencilOpDirty = true;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10978. get: function () {
  10979. return this._stencilOpStencilDepthPass;
  10980. },
  10981. set: function (value) {
  10982. if (this._stencilOpStencilDepthPass === value) {
  10983. return;
  10984. }
  10985. this._stencilOpStencilDepthPass = value;
  10986. this._isStencilOpDirty = true;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10992. get: function () {
  10993. return this._stencilMask;
  10994. },
  10995. set: function (value) {
  10996. if (this._stencilMask === value) {
  10997. return;
  10998. }
  10999. this._stencilMask = value;
  11000. this._isStencilMaskDirty = true;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11006. get: function () {
  11007. return this._stencilTest;
  11008. },
  11009. set: function (value) {
  11010. if (this._stencilTest === value) {
  11011. return;
  11012. }
  11013. this._stencilTest = value;
  11014. this._isStencilTestDirty = true;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. _StencilState.prototype.reset = function () {
  11020. this._stencilTest = false;
  11021. this._stencilMask = 0xFF;
  11022. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11023. this._stencilFuncRef = 1;
  11024. this._stencilFuncMask = 0xFF;
  11025. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11026. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11027. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11028. this._isStencilTestDirty = true;
  11029. this._isStencilMaskDirty = true;
  11030. this._isStencilFuncDirty = true;
  11031. this._isStencilOpDirty = true;
  11032. };
  11033. _StencilState.prototype.apply = function (gl) {
  11034. if (!this.isDirty) {
  11035. return;
  11036. }
  11037. // Stencil test
  11038. if (this._isStencilTestDirty) {
  11039. if (this.stencilTest) {
  11040. gl.enable(gl.STENCIL_TEST);
  11041. }
  11042. else {
  11043. gl.disable(gl.STENCIL_TEST);
  11044. }
  11045. this._isStencilTestDirty = false;
  11046. }
  11047. // Stencil mask
  11048. if (this._isStencilMaskDirty) {
  11049. gl.stencilMask(this.stencilMask);
  11050. this._isStencilMaskDirty = false;
  11051. }
  11052. // Stencil func
  11053. if (this._isStencilFuncDirty) {
  11054. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11055. this._isStencilFuncDirty = false;
  11056. }
  11057. // Stencil op
  11058. if (this._isStencilOpDirty) {
  11059. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11060. this._isStencilOpDirty = false;
  11061. }
  11062. };
  11063. return _StencilState;
  11064. }());
  11065. BABYLON._StencilState = _StencilState;
  11066. })(BABYLON || (BABYLON = {}));
  11067. //# sourceMappingURL=babylon.stencilState.js.map
  11068. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11070. s = arguments[i];
  11071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11072. t[p] = s[p];
  11073. }
  11074. return t;
  11075. };
  11076. var BABYLON;
  11077. (function (BABYLON) {
  11078. /**
  11079. * Keeps track of all the buffer info used in engine.
  11080. */
  11081. var BufferPointer = /** @class */ (function () {
  11082. function BufferPointer() {
  11083. }
  11084. return BufferPointer;
  11085. }());
  11086. /**
  11087. * Interface for attribute information associated with buffer instanciation
  11088. */
  11089. var InstancingAttributeInfo = /** @class */ (function () {
  11090. function InstancingAttributeInfo() {
  11091. }
  11092. return InstancingAttributeInfo;
  11093. }());
  11094. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11095. /**
  11096. * Define options used to create a render target texture
  11097. */
  11098. var RenderTargetCreationOptions = /** @class */ (function () {
  11099. function RenderTargetCreationOptions() {
  11100. }
  11101. return RenderTargetCreationOptions;
  11102. }());
  11103. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11104. /**
  11105. * Define options used to create a depth texture
  11106. */
  11107. var DepthTextureCreationOptions = /** @class */ (function () {
  11108. function DepthTextureCreationOptions() {
  11109. }
  11110. return DepthTextureCreationOptions;
  11111. }());
  11112. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11113. /**
  11114. * Class used to describe the capabilities of the engine relatively to the current browser
  11115. */
  11116. var EngineCapabilities = /** @class */ (function () {
  11117. function EngineCapabilities() {
  11118. }
  11119. return EngineCapabilities;
  11120. }());
  11121. BABYLON.EngineCapabilities = EngineCapabilities;
  11122. /**
  11123. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11124. */
  11125. var Engine = /** @class */ (function () {
  11126. /**
  11127. * Creates a new engine
  11128. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11129. * @param antialias defines enable antialiasing (default: false)
  11130. * @param options defines further options to be sent to the getContext() function
  11131. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11132. */
  11133. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11134. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11135. var _this = this;
  11136. // Public members
  11137. /**
  11138. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11139. */
  11140. this.forcePOTTextures = false;
  11141. /**
  11142. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11143. */
  11144. this.isFullscreen = false;
  11145. /**
  11146. * Gets a boolean indicating if the pointer is currently locked
  11147. */
  11148. this.isPointerLock = false;
  11149. /**
  11150. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11151. */
  11152. this.cullBackFaces = true;
  11153. /**
  11154. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11155. */
  11156. this.renderEvenInBackground = true;
  11157. /**
  11158. * Gets or sets a boolean indicating that cache can be kept between frames
  11159. */
  11160. this.preventCacheWipeBetweenFrames = false;
  11161. /**
  11162. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11163. **/
  11164. this.enableOfflineSupport = false;
  11165. /**
  11166. * 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)
  11167. **/
  11168. this.disableManifestCheck = false;
  11169. /**
  11170. * Gets the list of created scenes
  11171. */
  11172. this.scenes = new Array();
  11173. /**
  11174. * Gets the list of created postprocesses
  11175. */
  11176. this.postProcesses = new Array();
  11177. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11178. this.validateShaderPrograms = false;
  11179. // Observables
  11180. /**
  11181. * Observable event triggered each time the rendering canvas is resized
  11182. */
  11183. this.onResizeObservable = new BABYLON.Observable();
  11184. /**
  11185. * Observable event triggered each time the canvas loses focus
  11186. */
  11187. this.onCanvasBlurObservable = new BABYLON.Observable();
  11188. /**
  11189. * Observable event triggered each time the canvas gains focus
  11190. */
  11191. this.onCanvasFocusObservable = new BABYLON.Observable();
  11192. /**
  11193. * Observable event triggered each time the canvas receives pointerout event
  11194. */
  11195. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11196. /**
  11197. * Observable event triggered before each texture is initialized
  11198. */
  11199. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11200. //WebVR
  11201. this._vrDisplay = undefined;
  11202. this._vrSupported = false;
  11203. this._vrExclusivePointerMode = false;
  11204. // Uniform buffers list
  11205. /**
  11206. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11207. */
  11208. this.disableUniformBuffers = false;
  11209. /** @hidden */
  11210. this._uniformBuffers = new Array();
  11211. // Observables
  11212. /**
  11213. * Observable raised when the engine begins a new frame
  11214. */
  11215. this.onBeginFrameObservable = new BABYLON.Observable();
  11216. /**
  11217. * Observable raised when the engine ends the current frame
  11218. */
  11219. this.onEndFrameObservable = new BABYLON.Observable();
  11220. /**
  11221. * Observable raised when the engine is about to compile a shader
  11222. */
  11223. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable raised when the engine has jsut compiled a shader
  11226. */
  11227. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11228. this._windowIsBackground = false;
  11229. this._webGLVersion = 1.0;
  11230. /** @hidden */
  11231. this._badOS = false;
  11232. /** @hidden */
  11233. this._badDesktopOS = false;
  11234. /**
  11235. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11236. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11237. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11238. */
  11239. this.disableTextureBindingOptimization = false;
  11240. /**
  11241. * Observable signaled when VR display mode changes
  11242. */
  11243. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11244. /**
  11245. * Observable signaled when VR request present is complete
  11246. */
  11247. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11248. /**
  11249. * Observable signaled when VR request present starts
  11250. */
  11251. this.onVRRequestPresentStart = new BABYLON.Observable();
  11252. this._colorWrite = true;
  11253. /** @hidden */
  11254. this._drawCalls = new BABYLON.PerfCounter();
  11255. /** @hidden */
  11256. this._textureCollisions = new BABYLON.PerfCounter();
  11257. this._renderingQueueLaunched = false;
  11258. this._activeRenderLoops = new Array();
  11259. // Deterministic lockstepMaxSteps
  11260. this._deterministicLockstep = false;
  11261. this._lockstepMaxSteps = 4;
  11262. // Lost context
  11263. /**
  11264. * Observable signaled when a context lost event is raised
  11265. */
  11266. this.onContextLostObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable signaled when a context restored event is raised
  11269. */
  11270. this.onContextRestoredObservable = new BABYLON.Observable();
  11271. this._contextWasLost = false;
  11272. this._doNotHandleContextLost = false;
  11273. // FPS
  11274. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11275. this._fps = 60;
  11276. this._deltaTime = 0;
  11277. /**
  11278. * Turn this value on if you want to pause FPS computation when in background
  11279. */
  11280. this.disablePerformanceMonitorInBackground = false;
  11281. // States
  11282. /** @hidden */
  11283. this._depthCullingState = new BABYLON._DepthCullingState();
  11284. /** @hidden */
  11285. this._stencilState = new BABYLON._StencilState();
  11286. /** @hidden */
  11287. this._alphaState = new BABYLON._AlphaState();
  11288. /** @hidden */
  11289. this._alphaMode = Engine.ALPHA_DISABLE;
  11290. // Cache
  11291. this._internalTexturesCache = new Array();
  11292. /** @hidden */
  11293. this._activeChannel = 0;
  11294. this._currentTextureChannel = -1;
  11295. /** @hidden */
  11296. this._boundTexturesCache = {};
  11297. this._compiledEffects = {};
  11298. this._vertexAttribArraysEnabled = [];
  11299. this._uintIndicesCurrentlySet = false;
  11300. this._currentBoundBuffer = new Array();
  11301. /** @hidden */
  11302. this._currentFramebuffer = null;
  11303. this._currentBufferPointers = new Array();
  11304. this._currentInstanceLocations = new Array();
  11305. this._currentInstanceBuffers = new Array();
  11306. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11307. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11308. this._vaoRecordInProgress = false;
  11309. this._mustWipeVertexAttributes = false;
  11310. this._nextFreeTextureSlots = new Array();
  11311. this._maxSimultaneousTextures = 0;
  11312. this._activeRequests = new Array();
  11313. // Hardware supported Compressed Textures
  11314. this._texturesSupported = new Array();
  11315. /**
  11316. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11317. */
  11318. this.premultipliedAlpha = true;
  11319. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11320. this._onVRFullScreenTriggered = function () {
  11321. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11322. //get the old size before we change
  11323. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11324. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11325. //get the width and height, change the render size
  11326. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11327. _this.setHardwareScalingLevel(1);
  11328. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11329. }
  11330. else {
  11331. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11332. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11333. }
  11334. };
  11335. this._unpackFlipYCached = null;
  11336. this._boundUniforms = {};
  11337. // Register promises
  11338. BABYLON.PromisePolyfill.Apply();
  11339. var canvas = null;
  11340. Engine.Instances.push(this);
  11341. if (!canvasOrContext) {
  11342. return;
  11343. }
  11344. options = options || {};
  11345. if (canvasOrContext.getContext) {
  11346. canvas = canvasOrContext;
  11347. this._renderingCanvas = canvas;
  11348. if (antialias != null) {
  11349. options.antialias = antialias;
  11350. }
  11351. if (options.deterministicLockstep === undefined) {
  11352. options.deterministicLockstep = false;
  11353. }
  11354. if (options.lockstepMaxSteps === undefined) {
  11355. options.lockstepMaxSteps = 4;
  11356. }
  11357. if (options.preserveDrawingBuffer === undefined) {
  11358. options.preserveDrawingBuffer = false;
  11359. }
  11360. if (options.audioEngine === undefined) {
  11361. options.audioEngine = true;
  11362. }
  11363. if (options.stencil === undefined) {
  11364. options.stencil = true;
  11365. }
  11366. if (options.premultipliedAlpha === false) {
  11367. this.premultipliedAlpha = false;
  11368. }
  11369. this._deterministicLockstep = options.deterministicLockstep;
  11370. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11371. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11372. // Exceptions
  11373. if (navigator && navigator.userAgent) {
  11374. var ua = navigator.userAgent;
  11375. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11376. var exception = _a[_i];
  11377. var key = exception.key;
  11378. var targets = exception.targets;
  11379. if (ua.indexOf(key) > -1) {
  11380. if (exception.capture && exception.captureConstraint) {
  11381. var capture = exception.capture;
  11382. var constraint = exception.captureConstraint;
  11383. var regex = new RegExp(capture);
  11384. var matches = regex.exec(ua);
  11385. if (matches && matches.length > 0) {
  11386. var capturedValue = parseInt(matches[matches.length - 1]);
  11387. if (capturedValue >= constraint) {
  11388. continue;
  11389. }
  11390. }
  11391. }
  11392. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11393. var target = targets_1[_b];
  11394. switch (target) {
  11395. case "uniformBuffer":
  11396. this.disableUniformBuffers = true;
  11397. break;
  11398. case "textureBindingOptimization":
  11399. this.disableTextureBindingOptimization = true;
  11400. break;
  11401. }
  11402. }
  11403. }
  11404. }
  11405. }
  11406. // GL
  11407. if (!options.disableWebGL2Support) {
  11408. try {
  11409. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11410. if (this._gl) {
  11411. this._webGLVersion = 2.0;
  11412. }
  11413. }
  11414. catch (e) {
  11415. // Do nothing
  11416. }
  11417. }
  11418. if (!this._gl) {
  11419. if (!canvas) {
  11420. throw new Error("The provided canvas is null or undefined.");
  11421. }
  11422. try {
  11423. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11424. }
  11425. catch (e) {
  11426. throw new Error("WebGL not supported");
  11427. }
  11428. }
  11429. if (!this._gl) {
  11430. throw new Error("WebGL not supported");
  11431. }
  11432. this._onCanvasFocus = function () {
  11433. _this.onCanvasFocusObservable.notifyObservers(_this);
  11434. };
  11435. this._onCanvasBlur = function () {
  11436. _this.onCanvasBlurObservable.notifyObservers(_this);
  11437. };
  11438. canvas.addEventListener("focus", this._onCanvasFocus);
  11439. canvas.addEventListener("blur", this._onCanvasBlur);
  11440. this._onBlur = function () {
  11441. if (_this.disablePerformanceMonitorInBackground) {
  11442. _this._performanceMonitor.disable();
  11443. }
  11444. _this._windowIsBackground = true;
  11445. };
  11446. this._onFocus = function () {
  11447. if (_this.disablePerformanceMonitorInBackground) {
  11448. _this._performanceMonitor.enable();
  11449. }
  11450. _this._windowIsBackground = false;
  11451. };
  11452. this._onCanvasPointerOut = function (ev) {
  11453. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11454. };
  11455. window.addEventListener("blur", this._onBlur);
  11456. window.addEventListener("focus", this._onFocus);
  11457. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11458. // Context lost
  11459. if (!this._doNotHandleContextLost) {
  11460. this._onContextLost = function (evt) {
  11461. evt.preventDefault();
  11462. _this._contextWasLost = true;
  11463. BABYLON.Tools.Warn("WebGL context lost.");
  11464. _this.onContextLostObservable.notifyObservers(_this);
  11465. };
  11466. this._onContextRestored = function (evt) {
  11467. // Adding a timeout to avoid race condition at browser level
  11468. setTimeout(function () {
  11469. // Rebuild gl context
  11470. _this._initGLContext();
  11471. // Rebuild effects
  11472. _this._rebuildEffects();
  11473. // Rebuild textures
  11474. _this._rebuildInternalTextures();
  11475. // Rebuild buffers
  11476. _this._rebuildBuffers();
  11477. // Cache
  11478. _this.wipeCaches(true);
  11479. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11480. _this.onContextRestoredObservable.notifyObservers(_this);
  11481. _this._contextWasLost = false;
  11482. }, 0);
  11483. };
  11484. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11485. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11486. }
  11487. }
  11488. else {
  11489. this._gl = canvasOrContext;
  11490. this._renderingCanvas = this._gl.canvas;
  11491. if (this._gl.renderbufferStorageMultisample) {
  11492. this._webGLVersion = 2.0;
  11493. }
  11494. options.stencil = this._gl.getContextAttributes().stencil;
  11495. }
  11496. // Viewport
  11497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11499. this.resize();
  11500. this._isStencilEnable = options.stencil ? true : false;
  11501. this._initGLContext();
  11502. if (canvas) {
  11503. // Fullscreen
  11504. this._onFullscreenChange = function () {
  11505. if (document.fullscreen !== undefined) {
  11506. _this.isFullscreen = document.fullscreen;
  11507. }
  11508. else if (document.mozFullScreen !== undefined) {
  11509. _this.isFullscreen = document.mozFullScreen;
  11510. }
  11511. else if (document.webkitIsFullScreen !== undefined) {
  11512. _this.isFullscreen = document.webkitIsFullScreen;
  11513. }
  11514. else if (document.msIsFullScreen !== undefined) {
  11515. _this.isFullscreen = document.msIsFullScreen;
  11516. }
  11517. // Pointer lock
  11518. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11519. canvas.requestPointerLock = canvas.requestPointerLock ||
  11520. canvas.msRequestPointerLock ||
  11521. canvas.mozRequestPointerLock ||
  11522. canvas.webkitRequestPointerLock;
  11523. if (canvas.requestPointerLock) {
  11524. canvas.requestPointerLock();
  11525. }
  11526. }
  11527. };
  11528. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11529. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11530. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11531. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11532. // Pointer lock
  11533. this._onPointerLockChange = function () {
  11534. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11535. document.webkitPointerLockElement === canvas ||
  11536. document.msPointerLockElement === canvas ||
  11537. document.pointerLockElement === canvas);
  11538. };
  11539. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11540. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11541. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11542. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11543. this._onVRDisplayPointerRestricted = function () {
  11544. if (canvas) {
  11545. canvas.requestPointerLock();
  11546. }
  11547. };
  11548. this._onVRDisplayPointerUnrestricted = function () {
  11549. document.exitPointerLock();
  11550. };
  11551. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11552. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11553. }
  11554. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11555. Engine.audioEngine = new BABYLON.AudioEngine();
  11556. }
  11557. // Prepare buffer pointers
  11558. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11559. this._currentBufferPointers[i] = new BufferPointer();
  11560. }
  11561. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11562. // Load WebVR Devices
  11563. if (options.autoEnableWebVR) {
  11564. this.initWebVR();
  11565. }
  11566. // Detect if we are running on a faulty buggy OS.
  11567. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11568. // Detect if we are running on a faulty buggy desktop OS.
  11569. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11570. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11571. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11572. }
  11573. Object.defineProperty(Engine, "LastCreatedEngine", {
  11574. /**
  11575. * Gets the latest created engine
  11576. */
  11577. get: function () {
  11578. if (Engine.Instances.length === 0) {
  11579. return null;
  11580. }
  11581. return Engine.Instances[Engine.Instances.length - 1];
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(Engine, "LastCreatedScene", {
  11587. /**
  11588. * Gets the latest created scene
  11589. */
  11590. get: function () {
  11591. var lastCreatedEngine = Engine.LastCreatedEngine;
  11592. if (!lastCreatedEngine) {
  11593. return null;
  11594. }
  11595. if (lastCreatedEngine.scenes.length === 0) {
  11596. return null;
  11597. }
  11598. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. /**
  11604. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11605. * @param flag defines which part of the materials must be marked as dirty
  11606. * @param predicate defines a predicate used to filter which materials should be affected
  11607. */
  11608. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11609. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11610. var engine = Engine.Instances[engineIndex];
  11611. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11612. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11613. }
  11614. }
  11615. };
  11616. Object.defineProperty(Engine, "Version", {
  11617. /**
  11618. * Returns the current version of the framework
  11619. */
  11620. get: function () {
  11621. return "3.3.0-alpha.11";
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11627. /**
  11628. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11629. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11630. */
  11631. get: function () {
  11632. return this._vrExclusivePointerMode;
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11638. /**
  11639. * Gets a boolean indicating that the engine supports uniform buffers
  11640. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11641. */
  11642. get: function () {
  11643. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11649. /**
  11650. * Gets a boolean indicating that only power of 2 textures are supported
  11651. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11652. */
  11653. get: function () {
  11654. return this._webGLVersion < 2 || this.forcePOTTextures;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11660. /**
  11661. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11662. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11663. */
  11664. get: function () {
  11665. return this._doNotHandleContextLost;
  11666. },
  11667. set: function (value) {
  11668. this._doNotHandleContextLost = value;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11674. /**
  11675. * Gets the performance monitor attached to this engine
  11676. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11677. */
  11678. get: function () {
  11679. return this._performanceMonitor;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11685. /**
  11686. * Gets the list of texture formats supported
  11687. */
  11688. get: function () {
  11689. return this._texturesSupported;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11695. /**
  11696. * Gets the list of texture formats in use
  11697. */
  11698. get: function () {
  11699. return this._textureFormatInUse;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine.prototype, "currentViewport", {
  11705. /**
  11706. * Gets the current viewport
  11707. */
  11708. get: function () {
  11709. return this._cachedViewport;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11715. /**
  11716. * Gets the default empty texture
  11717. */
  11718. get: function () {
  11719. if (!this._emptyTexture) {
  11720. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11721. }
  11722. return this._emptyTexture;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11728. /**
  11729. * Gets the default empty 3D texture
  11730. */
  11731. get: function () {
  11732. if (!this._emptyTexture3D) {
  11733. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11734. }
  11735. return this._emptyTexture3D;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11741. /**
  11742. * Gets the default empty cube texture
  11743. */
  11744. get: function () {
  11745. if (!this._emptyCubeTexture) {
  11746. var faceData = new Uint8Array(4);
  11747. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11748. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11749. }
  11750. return this._emptyCubeTexture;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Engine.prototype._rebuildInternalTextures = function () {
  11756. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11757. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11758. var internalTexture = currentState_1[_i];
  11759. internalTexture._rebuild();
  11760. }
  11761. };
  11762. Engine.prototype._rebuildEffects = function () {
  11763. for (var key in this._compiledEffects) {
  11764. var effect = this._compiledEffects[key];
  11765. effect._prepareEffect();
  11766. }
  11767. BABYLON.Effect.ResetCache();
  11768. };
  11769. Engine.prototype._rebuildBuffers = function () {
  11770. // Index / Vertex
  11771. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11772. var scene = _a[_i];
  11773. scene.resetCachedMaterial();
  11774. scene._rebuildGeometries();
  11775. scene._rebuildTextures();
  11776. }
  11777. // Uniforms
  11778. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11779. var uniformBuffer = _c[_b];
  11780. uniformBuffer._rebuild();
  11781. }
  11782. };
  11783. Engine.prototype._initGLContext = function () {
  11784. // Caps
  11785. this._caps = new EngineCapabilities();
  11786. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11787. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11788. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11789. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11790. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11791. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11792. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11793. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11794. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11795. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11796. // Infos
  11797. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11798. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11799. if (rendererInfo != null) {
  11800. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11801. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11802. }
  11803. if (!this._glVendor) {
  11804. this._glVendor = "Unknown vendor";
  11805. }
  11806. if (!this._glRenderer) {
  11807. this._glRenderer = "Unknown renderer";
  11808. }
  11809. // Constants
  11810. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11811. if (this._gl.RGBA16F !== 0x881A) {
  11812. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11813. }
  11814. if (this._gl.RGBA32F !== 0x8814) {
  11815. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11816. }
  11817. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11818. this._gl.DEPTH24_STENCIL8 = 35056;
  11819. }
  11820. // Extensions
  11821. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11822. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11823. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11824. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11825. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11826. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11827. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11828. 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');
  11829. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11830. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11831. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11832. this._caps.highPrecisionShaderSupported = true;
  11833. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11834. if (this._caps.timerQuery) {
  11835. if (this._webGLVersion === 1) {
  11836. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11837. }
  11838. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11839. }
  11840. // Checks if some of the format renders first to allow the use of webgl inspector.
  11841. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11842. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11843. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11844. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11845. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11846. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11847. if (this._webGLVersion > 1) {
  11848. this._gl.HALF_FLOAT_OES = 0x140B;
  11849. }
  11850. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11851. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11852. // Draw buffers
  11853. if (this._webGLVersion > 1) {
  11854. this._caps.drawBuffersExtension = true;
  11855. }
  11856. else {
  11857. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11858. if (drawBuffersExtension !== null) {
  11859. this._caps.drawBuffersExtension = true;
  11860. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11861. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11862. for (var i = 0; i < 16; i++) {
  11863. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11864. }
  11865. }
  11866. else {
  11867. this._caps.drawBuffersExtension = false;
  11868. }
  11869. }
  11870. // Depth Texture
  11871. if (this._webGLVersion > 1) {
  11872. this._caps.depthTextureExtension = true;
  11873. }
  11874. else {
  11875. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11876. if (depthTextureExtension != null) {
  11877. this._caps.depthTextureExtension = true;
  11878. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11879. }
  11880. }
  11881. // Vertex array object
  11882. if (this._webGLVersion > 1) {
  11883. this._caps.vertexArrayObject = true;
  11884. }
  11885. else {
  11886. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11887. if (vertexArrayObjectExtension != null) {
  11888. this._caps.vertexArrayObject = true;
  11889. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11890. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11891. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11892. }
  11893. else {
  11894. this._caps.vertexArrayObject = false;
  11895. }
  11896. }
  11897. // Instances count
  11898. if (this._webGLVersion > 1) {
  11899. this._caps.instancedArrays = true;
  11900. }
  11901. else {
  11902. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11903. if (instanceExtension != null) {
  11904. this._caps.instancedArrays = true;
  11905. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11906. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11907. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11908. }
  11909. else {
  11910. this._caps.instancedArrays = false;
  11911. }
  11912. }
  11913. // Intelligently add supported compressed formats in order to check for.
  11914. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11915. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11916. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11917. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11918. if (this._caps.astc)
  11919. this.texturesSupported.push('-astc.ktx');
  11920. if (this._caps.s3tc)
  11921. this.texturesSupported.push('-dxt.ktx');
  11922. if (this._caps.pvrtc)
  11923. this.texturesSupported.push('-pvrtc.ktx');
  11924. if (this._caps.etc2)
  11925. this.texturesSupported.push('-etc2.ktx');
  11926. if (this._caps.etc1)
  11927. this.texturesSupported.push('-etc1.ktx');
  11928. if (this._gl.getShaderPrecisionFormat) {
  11929. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11930. if (highp) {
  11931. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11932. }
  11933. }
  11934. // Depth buffer
  11935. this.setDepthBuffer(true);
  11936. this.setDepthFunctionToLessOrEqual();
  11937. this.setDepthWrite(true);
  11938. // Texture maps
  11939. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11940. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11941. this._nextFreeTextureSlots.push(slot);
  11942. }
  11943. };
  11944. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11945. /**
  11946. * Gets version of the current webGL context
  11947. */
  11948. get: function () {
  11949. return this._webGLVersion;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11955. /**
  11956. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11957. */
  11958. get: function () {
  11959. return this._isStencilEnable;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Engine.prototype._prepareWorkingCanvas = function () {
  11965. if (this._workingCanvas) {
  11966. return;
  11967. }
  11968. this._workingCanvas = document.createElement("canvas");
  11969. var context = this._workingCanvas.getContext("2d");
  11970. if (context) {
  11971. this._workingContext = context;
  11972. }
  11973. };
  11974. /**
  11975. * Reset the texture cache to empty state
  11976. */
  11977. Engine.prototype.resetTextureCache = function () {
  11978. for (var key in this._boundTexturesCache) {
  11979. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  11980. continue;
  11981. }
  11982. var boundTexture = this._boundTexturesCache[key];
  11983. if (boundTexture) {
  11984. this._removeDesignatedSlot(boundTexture);
  11985. }
  11986. this._boundTexturesCache[key] = null;
  11987. }
  11988. if (!this.disableTextureBindingOptimization) {
  11989. this._nextFreeTextureSlots = [];
  11990. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11991. this._nextFreeTextureSlots.push(slot);
  11992. }
  11993. }
  11994. this._currentTextureChannel = -1;
  11995. };
  11996. /**
  11997. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11998. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11999. * @returns true if engine is in deterministic lock step mode
  12000. */
  12001. Engine.prototype.isDeterministicLockStep = function () {
  12002. return this._deterministicLockstep;
  12003. };
  12004. /**
  12005. * Gets the max steps when engine is running in deterministic lock step
  12006. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12007. * @returns the max steps
  12008. */
  12009. Engine.prototype.getLockstepMaxSteps = function () {
  12010. return this._lockstepMaxSteps;
  12011. };
  12012. /**
  12013. * Gets an object containing information about the current webGL context
  12014. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12015. */
  12016. Engine.prototype.getGlInfo = function () {
  12017. return {
  12018. vendor: this._glVendor,
  12019. renderer: this._glRenderer,
  12020. version: this._glVersion
  12021. };
  12022. };
  12023. /**
  12024. * Gets current aspect ratio
  12025. * @param camera defines the camera to use to get the aspect ratio
  12026. * @param useScreen defines if screen size must be used (or the current render target if any)
  12027. * @returns a number defining the aspect ratio
  12028. */
  12029. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12030. if (useScreen === void 0) { useScreen = false; }
  12031. var viewport = camera.viewport;
  12032. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12033. };
  12034. /**
  12035. * Gets current screen aspect ratio
  12036. * @returns a number defining the aspect ratio
  12037. */
  12038. Engine.prototype.getScreenAspectRatio = function () {
  12039. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12040. };
  12041. /**
  12042. * Gets the current render width
  12043. * @param useScreen defines if screen size must be used (or the current render target if any)
  12044. * @returns a number defining the current render width
  12045. */
  12046. Engine.prototype.getRenderWidth = function (useScreen) {
  12047. if (useScreen === void 0) { useScreen = false; }
  12048. if (!useScreen && this._currentRenderTarget) {
  12049. return this._currentRenderTarget.width;
  12050. }
  12051. return this._gl.drawingBufferWidth;
  12052. };
  12053. /**
  12054. * Gets the current render height
  12055. * @param useScreen defines if screen size must be used (or the current render target if any)
  12056. * @returns a number defining the current render height
  12057. */
  12058. Engine.prototype.getRenderHeight = function (useScreen) {
  12059. if (useScreen === void 0) { useScreen = false; }
  12060. if (!useScreen && this._currentRenderTarget) {
  12061. return this._currentRenderTarget.height;
  12062. }
  12063. return this._gl.drawingBufferHeight;
  12064. };
  12065. /**
  12066. * Gets the HTML canvas attached with the current webGL context
  12067. * @returns a HTML canvas
  12068. */
  12069. Engine.prototype.getRenderingCanvas = function () {
  12070. return this._renderingCanvas;
  12071. };
  12072. /**
  12073. * Gets the client rect of the HTML canvas attached with the current webGL context
  12074. * @returns a client rectanglee
  12075. */
  12076. Engine.prototype.getRenderingCanvasClientRect = function () {
  12077. if (!this._renderingCanvas) {
  12078. return null;
  12079. }
  12080. return this._renderingCanvas.getBoundingClientRect();
  12081. };
  12082. /**
  12083. * Defines the hardware scaling level.
  12084. * By default the hardware scaling level is computed from the window device ratio.
  12085. * 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.
  12086. * @param level defines the level to use
  12087. */
  12088. Engine.prototype.setHardwareScalingLevel = function (level) {
  12089. this._hardwareScalingLevel = level;
  12090. this.resize();
  12091. };
  12092. /**
  12093. * Gets the current hardware scaling level.
  12094. * By default the hardware scaling level is computed from the window device ratio.
  12095. * 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.
  12096. * @returns a number indicating the current hardware scaling level
  12097. */
  12098. Engine.prototype.getHardwareScalingLevel = function () {
  12099. return this._hardwareScalingLevel;
  12100. };
  12101. /**
  12102. * Gets the list of loaded textures
  12103. * @returns an array containing all loaded textures
  12104. */
  12105. Engine.prototype.getLoadedTexturesCache = function () {
  12106. return this._internalTexturesCache;
  12107. };
  12108. /**
  12109. * Gets the object containing all engine capabilities
  12110. * @returns the EngineCapabilities object
  12111. */
  12112. Engine.prototype.getCaps = function () {
  12113. return this._caps;
  12114. };
  12115. Object.defineProperty(Engine.prototype, "drawCalls", {
  12116. /** @hidden */
  12117. get: function () {
  12118. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12119. return 0;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12125. /** @hidden */
  12126. get: function () {
  12127. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12128. return null;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. /**
  12134. * Gets the current depth function
  12135. * @returns a number defining the depth function
  12136. */
  12137. Engine.prototype.getDepthFunction = function () {
  12138. return this._depthCullingState.depthFunc;
  12139. };
  12140. /**
  12141. * Sets the current depth function
  12142. * @param depthFunc defines the function to use
  12143. */
  12144. Engine.prototype.setDepthFunction = function (depthFunc) {
  12145. this._depthCullingState.depthFunc = depthFunc;
  12146. };
  12147. /**
  12148. * Sets the current depth function to GREATER
  12149. */
  12150. Engine.prototype.setDepthFunctionToGreater = function () {
  12151. this._depthCullingState.depthFunc = this._gl.GREATER;
  12152. };
  12153. /**
  12154. * Sets the current depth function to GEQUAL
  12155. */
  12156. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12157. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12158. };
  12159. /**
  12160. * Sets the current depth function to LESS
  12161. */
  12162. Engine.prototype.setDepthFunctionToLess = function () {
  12163. this._depthCullingState.depthFunc = this._gl.LESS;
  12164. };
  12165. /**
  12166. * Sets the current depth function to LEQUAL
  12167. */
  12168. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12169. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12170. };
  12171. /**
  12172. * Gets a boolean indicating if stencil buffer is enabled
  12173. * @returns the current stencil buffer state
  12174. */
  12175. Engine.prototype.getStencilBuffer = function () {
  12176. return this._stencilState.stencilTest;
  12177. };
  12178. /**
  12179. * Enable or disable the stencil buffer
  12180. * @param enable defines if the stencil buffer must be enabled or disabled
  12181. */
  12182. Engine.prototype.setStencilBuffer = function (enable) {
  12183. this._stencilState.stencilTest = enable;
  12184. };
  12185. /**
  12186. * Gets the current stencil mask
  12187. * @returns a number defining the new stencil mask to use
  12188. */
  12189. Engine.prototype.getStencilMask = function () {
  12190. return this._stencilState.stencilMask;
  12191. };
  12192. /**
  12193. * Sets the current stencil mask
  12194. * @param mask defines the new stencil mask to use
  12195. */
  12196. Engine.prototype.setStencilMask = function (mask) {
  12197. this._stencilState.stencilMask = mask;
  12198. };
  12199. /**
  12200. * Gets the current stencil function
  12201. * @returns a number defining the stencil function to use
  12202. */
  12203. Engine.prototype.getStencilFunction = function () {
  12204. return this._stencilState.stencilFunc;
  12205. };
  12206. /**
  12207. * Gets the current stencil reference value
  12208. * @returns a number defining the stencil reference value to use
  12209. */
  12210. Engine.prototype.getStencilFunctionReference = function () {
  12211. return this._stencilState.stencilFuncRef;
  12212. };
  12213. /**
  12214. * Gets the current stencil mask
  12215. * @returns a number defining the stencil mask to use
  12216. */
  12217. Engine.prototype.getStencilFunctionMask = function () {
  12218. return this._stencilState.stencilFuncMask;
  12219. };
  12220. /**
  12221. * Sets the current stencil function
  12222. * @param stencilFunc defines the new stencil function to use
  12223. */
  12224. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12225. this._stencilState.stencilFunc = stencilFunc;
  12226. };
  12227. /**
  12228. * Sets the current stencil reference
  12229. * @param reference defines the new stencil reference to use
  12230. */
  12231. Engine.prototype.setStencilFunctionReference = function (reference) {
  12232. this._stencilState.stencilFuncRef = reference;
  12233. };
  12234. /**
  12235. * Sets the current stencil mask
  12236. * @param mask defines the new stencil mask to use
  12237. */
  12238. Engine.prototype.setStencilFunctionMask = function (mask) {
  12239. this._stencilState.stencilFuncMask = mask;
  12240. };
  12241. /**
  12242. * Gets the current stencil operation when stencil fails
  12243. * @returns a number defining stencil operation to use when stencil fails
  12244. */
  12245. Engine.prototype.getStencilOperationFail = function () {
  12246. return this._stencilState.stencilOpStencilFail;
  12247. };
  12248. /**
  12249. * Gets the current stencil operation when depth fails
  12250. * @returns a number defining stencil operation to use when depth fails
  12251. */
  12252. Engine.prototype.getStencilOperationDepthFail = function () {
  12253. return this._stencilState.stencilOpDepthFail;
  12254. };
  12255. /**
  12256. * Gets the current stencil operation when stencil passes
  12257. * @returns a number defining stencil operation to use when stencil passes
  12258. */
  12259. Engine.prototype.getStencilOperationPass = function () {
  12260. return this._stencilState.stencilOpStencilDepthPass;
  12261. };
  12262. /**
  12263. * Sets the stencil operation to use when stencil fails
  12264. * @param operation defines the stencil operation to use when stencil fails
  12265. */
  12266. Engine.prototype.setStencilOperationFail = function (operation) {
  12267. this._stencilState.stencilOpStencilFail = operation;
  12268. };
  12269. /**
  12270. * Sets the stencil operation to use when depth fails
  12271. * @param operation defines the stencil operation to use when depth fails
  12272. */
  12273. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12274. this._stencilState.stencilOpDepthFail = operation;
  12275. };
  12276. /**
  12277. * Sets the stencil operation to use when stencil passes
  12278. * @param operation defines the stencil operation to use when stencil passes
  12279. */
  12280. Engine.prototype.setStencilOperationPass = function (operation) {
  12281. this._stencilState.stencilOpStencilDepthPass = operation;
  12282. };
  12283. /**
  12284. * Sets a boolean indicating if the dithering state is enabled or disabled
  12285. * @param value defines the dithering state
  12286. */
  12287. Engine.prototype.setDitheringState = function (value) {
  12288. if (value) {
  12289. this._gl.enable(this._gl.DITHER);
  12290. }
  12291. else {
  12292. this._gl.disable(this._gl.DITHER);
  12293. }
  12294. };
  12295. /**
  12296. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12297. * @param value defines the rasterizer state
  12298. */
  12299. Engine.prototype.setRasterizerState = function (value) {
  12300. if (value) {
  12301. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12302. }
  12303. else {
  12304. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12305. }
  12306. };
  12307. /**
  12308. * stop executing a render loop function and remove it from the execution array
  12309. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12310. */
  12311. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12312. if (!renderFunction) {
  12313. this._activeRenderLoops = [];
  12314. return;
  12315. }
  12316. var index = this._activeRenderLoops.indexOf(renderFunction);
  12317. if (index >= 0) {
  12318. this._activeRenderLoops.splice(index, 1);
  12319. }
  12320. };
  12321. /** @hidden */
  12322. Engine.prototype._renderLoop = function () {
  12323. if (!this._contextWasLost) {
  12324. var shouldRender = true;
  12325. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12326. shouldRender = false;
  12327. }
  12328. if (shouldRender) {
  12329. // Start new frame
  12330. this.beginFrame();
  12331. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12332. var renderFunction = this._activeRenderLoops[index];
  12333. renderFunction();
  12334. }
  12335. // Present
  12336. this.endFrame();
  12337. }
  12338. }
  12339. if (this._activeRenderLoops.length > 0) {
  12340. // Register new frame
  12341. var requester = null;
  12342. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12343. requester = this._vrDisplay;
  12344. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12345. }
  12346. else {
  12347. this._renderingQueueLaunched = false;
  12348. }
  12349. };
  12350. /**
  12351. * Register and execute a render loop. The engine can have more than one render function
  12352. * @param renderFunction defines the function to continuously execute
  12353. */
  12354. Engine.prototype.runRenderLoop = function (renderFunction) {
  12355. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12356. return;
  12357. }
  12358. this._activeRenderLoops.push(renderFunction);
  12359. if (!this._renderingQueueLaunched) {
  12360. this._renderingQueueLaunched = true;
  12361. this._bindedRenderFunction = this._renderLoop.bind(this);
  12362. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12363. }
  12364. };
  12365. /**
  12366. * Toggle full screen mode
  12367. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12368. * @param options defines an option object to be sent to the requestFullscreen function
  12369. */
  12370. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12371. if (this.isFullscreen) {
  12372. BABYLON.Tools.ExitFullscreen();
  12373. }
  12374. else {
  12375. this._pointerLockRequested = requestPointerLock;
  12376. if (this._renderingCanvas) {
  12377. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12378. }
  12379. }
  12380. };
  12381. /**
  12382. * Clear the current render buffer or the current render target (if any is set up)
  12383. * @param color defines the color to use
  12384. * @param backBuffer defines if the back buffer must be cleared
  12385. * @param depth defines if the depth buffer must be cleared
  12386. * @param stencil defines if the stencil buffer must be cleared
  12387. */
  12388. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12389. if (stencil === void 0) { stencil = false; }
  12390. this.applyStates();
  12391. var mode = 0;
  12392. if (backBuffer && color) {
  12393. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12394. mode |= this._gl.COLOR_BUFFER_BIT;
  12395. }
  12396. if (depth) {
  12397. this._gl.clearDepth(1.0);
  12398. mode |= this._gl.DEPTH_BUFFER_BIT;
  12399. }
  12400. if (stencil) {
  12401. this._gl.clearStencil(0);
  12402. mode |= this._gl.STENCIL_BUFFER_BIT;
  12403. }
  12404. this._gl.clear(mode);
  12405. };
  12406. /**
  12407. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12408. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12409. * @param y defines the y-coordinate of the corner of the clear rectangle
  12410. * @param width defines the width of the clear rectangle
  12411. * @param height defines the height of the clear rectangle
  12412. * @param clearColor defines the clear color
  12413. */
  12414. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12415. var gl = this._gl;
  12416. // Save state
  12417. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12418. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12419. // Change state
  12420. gl.enable(gl.SCISSOR_TEST);
  12421. gl.scissor(x, y, width, height);
  12422. // Clear
  12423. this.clear(clearColor, true, true, true);
  12424. // Restore state
  12425. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12426. if (curScissor === true) {
  12427. gl.enable(gl.SCISSOR_TEST);
  12428. }
  12429. else {
  12430. gl.disable(gl.SCISSOR_TEST);
  12431. }
  12432. };
  12433. /** @hidden */
  12434. Engine.prototype._viewport = function (x, y, width, height) {
  12435. if (x !== this._viewportCached.x ||
  12436. y !== this._viewportCached.y ||
  12437. width !== this._viewportCached.z ||
  12438. height !== this._viewportCached.w) {
  12439. this._viewportCached.x = x;
  12440. this._viewportCached.y = y;
  12441. this._viewportCached.z = width;
  12442. this._viewportCached.w = height;
  12443. this._gl.viewport(x, y, width, height);
  12444. }
  12445. };
  12446. /**
  12447. * Set the WebGL's viewport
  12448. * @param viewport defines the viewport element to be used
  12449. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12450. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12451. */
  12452. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12453. var width = requiredWidth || this.getRenderWidth();
  12454. var height = requiredHeight || this.getRenderHeight();
  12455. var x = viewport.x || 0;
  12456. var y = viewport.y || 0;
  12457. this._cachedViewport = viewport;
  12458. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12459. };
  12460. /**
  12461. * Directly set the WebGL Viewport
  12462. * @param x defines the x coordinate of the viewport (in screen space)
  12463. * @param y defines the y coordinate of the viewport (in screen space)
  12464. * @param width defines the width of the viewport (in screen space)
  12465. * @param height defines the height of the viewport (in screen space)
  12466. * @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
  12467. */
  12468. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12469. var currentViewport = this._cachedViewport;
  12470. this._cachedViewport = null;
  12471. this._viewport(x, y, width, height);
  12472. return currentViewport;
  12473. };
  12474. /**
  12475. * Begin a new frame
  12476. */
  12477. Engine.prototype.beginFrame = function () {
  12478. this.onBeginFrameObservable.notifyObservers(this);
  12479. this._measureFps();
  12480. };
  12481. /**
  12482. * Enf the current frame
  12483. */
  12484. Engine.prototype.endFrame = function () {
  12485. // Force a flush in case we are using a bad OS.
  12486. if (this._badOS) {
  12487. this.flushFramebuffer();
  12488. }
  12489. // Submit frame to the vr device, if enabled
  12490. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12491. // TODO: We should only submit the frame if we read frameData successfully.
  12492. this._vrDisplay.submitFrame();
  12493. }
  12494. this.onEndFrameObservable.notifyObservers(this);
  12495. };
  12496. /**
  12497. * Resize the view according to the canvas' size
  12498. */
  12499. Engine.prototype.resize = function () {
  12500. // We're not resizing the size of the canvas while in VR mode & presenting
  12501. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12502. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12503. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12504. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12505. }
  12506. };
  12507. /**
  12508. * Force a specific size of the canvas
  12509. * @param width defines the new canvas' width
  12510. * @param height defines the new canvas' height
  12511. */
  12512. Engine.prototype.setSize = function (width, height) {
  12513. if (!this._renderingCanvas) {
  12514. return;
  12515. }
  12516. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12517. return;
  12518. }
  12519. this._renderingCanvas.width = width;
  12520. this._renderingCanvas.height = height;
  12521. for (var index = 0; index < this.scenes.length; index++) {
  12522. var scene = this.scenes[index];
  12523. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12524. var cam = scene.cameras[camIndex];
  12525. cam._currentRenderId = 0;
  12526. }
  12527. }
  12528. if (this.onResizeObservable.hasObservers) {
  12529. this.onResizeObservable.notifyObservers(this);
  12530. }
  12531. };
  12532. // WebVR functions
  12533. /**
  12534. * Gets a boolean indicating if a webVR device was detected
  12535. * @returns true if a webVR device was detected
  12536. */
  12537. Engine.prototype.isVRDevicePresent = function () {
  12538. return !!this._vrDisplay;
  12539. };
  12540. /**
  12541. * Gets the current webVR device
  12542. * @returns the current webVR device (or null)
  12543. */
  12544. Engine.prototype.getVRDevice = function () {
  12545. return this._vrDisplay;
  12546. };
  12547. /**
  12548. * Initializes a webVR display and starts listening to display change events
  12549. * The onVRDisplayChangedObservable will be notified upon these changes
  12550. * @returns The onVRDisplayChangedObservable
  12551. */
  12552. Engine.prototype.initWebVR = function () {
  12553. this.initWebVRAsync();
  12554. return this.onVRDisplayChangedObservable;
  12555. };
  12556. /**
  12557. * Initializes a webVR display and starts listening to display change events
  12558. * The onVRDisplayChangedObservable will be notified upon these changes
  12559. * @returns A promise containing a VRDisplay and if vr is supported
  12560. */
  12561. Engine.prototype.initWebVRAsync = function () {
  12562. var _this = this;
  12563. var notifyObservers = function () {
  12564. var eventArgs = {
  12565. vrDisplay: _this._vrDisplay,
  12566. vrSupported: _this._vrSupported
  12567. };
  12568. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12569. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12570. };
  12571. if (!this._onVrDisplayConnect) {
  12572. this._onVrDisplayConnect = function (event) {
  12573. _this._vrDisplay = event.display;
  12574. notifyObservers();
  12575. };
  12576. this._onVrDisplayDisconnect = function () {
  12577. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12578. _this._vrDisplay = undefined;
  12579. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12580. notifyObservers();
  12581. };
  12582. this._onVrDisplayPresentChange = function () {
  12583. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12584. };
  12585. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12586. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12587. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12588. }
  12589. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12590. this._webVRInitPromise.then(notifyObservers);
  12591. return this._webVRInitPromise;
  12592. };
  12593. /**
  12594. * Call this function to switch to webVR mode
  12595. * Will do nothing if webVR is not supported or if there is no webVR device
  12596. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12597. */
  12598. Engine.prototype.enableVR = function () {
  12599. var _this = this;
  12600. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12601. var onResolved = function () {
  12602. _this.onVRRequestPresentComplete.notifyObservers(true);
  12603. _this._onVRFullScreenTriggered();
  12604. };
  12605. var onRejected = function () {
  12606. _this.onVRRequestPresentComplete.notifyObservers(false);
  12607. };
  12608. this.onVRRequestPresentStart.notifyObservers(this);
  12609. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12610. }
  12611. };
  12612. /**
  12613. * Call this function to leave webVR mode
  12614. * Will do nothing if webVR is not supported or if there is no webVR device
  12615. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12616. */
  12617. Engine.prototype.disableVR = function () {
  12618. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12619. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12620. }
  12621. };
  12622. Engine.prototype._getVRDisplaysAsync = function () {
  12623. var _this = this;
  12624. return new Promise(function (res, rej) {
  12625. if (navigator.getVRDisplays) {
  12626. navigator.getVRDisplays().then(function (devices) {
  12627. _this._vrSupported = true;
  12628. // note that devices may actually be an empty array. This is fine;
  12629. // we expect this._vrDisplay to be undefined in this case.
  12630. _this._vrDisplay = devices[0];
  12631. res({
  12632. vrDisplay: _this._vrDisplay,
  12633. vrSupported: _this._vrSupported
  12634. });
  12635. });
  12636. }
  12637. else {
  12638. _this._vrDisplay = undefined;
  12639. _this._vrSupported = false;
  12640. res({
  12641. vrDisplay: _this._vrDisplay,
  12642. vrSupported: _this._vrSupported
  12643. });
  12644. }
  12645. });
  12646. };
  12647. /**
  12648. * Binds the frame buffer to the specified texture.
  12649. * @param texture The texture to render to or null for the default canvas
  12650. * @param faceIndex The face of the texture to render to in case of cube texture
  12651. * @param requiredWidth The width of the target to render to
  12652. * @param requiredHeight The height of the target to render to
  12653. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12654. * @param depthStencilTexture The depth stencil texture to use to render
  12655. * @param lodLevel defines le lod level to bind to the frame buffer
  12656. */
  12657. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12658. if (lodLevel === void 0) { lodLevel = 0; }
  12659. if (this._currentRenderTarget) {
  12660. this.unBindFramebuffer(this._currentRenderTarget);
  12661. }
  12662. this._currentRenderTarget = texture;
  12663. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12664. var gl = this._gl;
  12665. if (texture.isCube) {
  12666. if (faceIndex === undefined) {
  12667. faceIndex = 0;
  12668. }
  12669. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12670. if (depthStencilTexture) {
  12671. if (depthStencilTexture._generateStencilBuffer) {
  12672. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12673. }
  12674. else {
  12675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12676. }
  12677. }
  12678. }
  12679. if (this._cachedViewport && !forceFullscreenViewport) {
  12680. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12681. }
  12682. else {
  12683. if (!requiredWidth) {
  12684. requiredWidth = texture.width;
  12685. if (lodLevel) {
  12686. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12687. }
  12688. }
  12689. if (!requiredHeight) {
  12690. requiredHeight = texture.height;
  12691. if (lodLevel) {
  12692. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12693. }
  12694. }
  12695. this._viewport(0, 0, requiredWidth, requiredHeight);
  12696. }
  12697. this.wipeCaches();
  12698. };
  12699. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12700. if (this._currentFramebuffer !== framebuffer) {
  12701. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12702. this._currentFramebuffer = framebuffer;
  12703. }
  12704. };
  12705. /**
  12706. * Unbind the current render target texture from the webGL context
  12707. * @param texture defines the render target texture to unbind
  12708. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12709. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12710. */
  12711. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12712. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12713. this._currentRenderTarget = null;
  12714. // If MSAA, we need to bitblt back to main texture
  12715. var gl = this._gl;
  12716. if (texture._MSAAFramebuffer) {
  12717. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12718. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12719. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12720. }
  12721. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12722. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12723. gl.generateMipmap(gl.TEXTURE_2D);
  12724. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12725. }
  12726. if (onBeforeUnbind) {
  12727. if (texture._MSAAFramebuffer) {
  12728. // Bind the correct framebuffer
  12729. this.bindUnboundFramebuffer(texture._framebuffer);
  12730. }
  12731. onBeforeUnbind();
  12732. }
  12733. this.bindUnboundFramebuffer(null);
  12734. };
  12735. /**
  12736. * Unbind a list of render target textures from the webGL context
  12737. * This is used only when drawBuffer extension or webGL2 are active
  12738. * @param textures defines the render target textures to unbind
  12739. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12740. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12741. */
  12742. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12743. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12744. this._currentRenderTarget = null;
  12745. // If MSAA, we need to bitblt back to main texture
  12746. var gl = this._gl;
  12747. if (textures[0]._MSAAFramebuffer) {
  12748. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12749. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12750. var attachments = textures[0]._attachments;
  12751. if (!attachments) {
  12752. attachments = new Array(textures.length);
  12753. textures[0]._attachments = attachments;
  12754. }
  12755. for (var i = 0; i < textures.length; i++) {
  12756. var texture = textures[i];
  12757. for (var j = 0; j < attachments.length; j++) {
  12758. attachments[j] = gl.NONE;
  12759. }
  12760. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12761. gl.readBuffer(attachments[i]);
  12762. gl.drawBuffers(attachments);
  12763. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12764. }
  12765. for (var i = 0; i < attachments.length; i++) {
  12766. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12767. }
  12768. gl.drawBuffers(attachments);
  12769. }
  12770. for (var i = 0; i < textures.length; i++) {
  12771. var texture = textures[i];
  12772. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12773. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12774. gl.generateMipmap(gl.TEXTURE_2D);
  12775. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12776. }
  12777. }
  12778. if (onBeforeUnbind) {
  12779. if (textures[0]._MSAAFramebuffer) {
  12780. // Bind the correct framebuffer
  12781. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12782. }
  12783. onBeforeUnbind();
  12784. }
  12785. this.bindUnboundFramebuffer(null);
  12786. };
  12787. /**
  12788. * Force the mipmap generation for the given render target texture
  12789. * @param texture defines the render target texture to use
  12790. */
  12791. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12792. if (texture.generateMipMaps) {
  12793. var gl = this._gl;
  12794. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12795. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12796. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12797. }
  12798. };
  12799. /**
  12800. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12801. */
  12802. Engine.prototype.flushFramebuffer = function () {
  12803. this._gl.flush();
  12804. };
  12805. /**
  12806. * Unbind the current render target and bind the default framebuffer
  12807. */
  12808. Engine.prototype.restoreDefaultFramebuffer = function () {
  12809. if (this._currentRenderTarget) {
  12810. this.unBindFramebuffer(this._currentRenderTarget);
  12811. }
  12812. else {
  12813. this.bindUnboundFramebuffer(null);
  12814. }
  12815. if (this._cachedViewport) {
  12816. this.setViewport(this._cachedViewport);
  12817. }
  12818. this.wipeCaches();
  12819. };
  12820. // UBOs
  12821. /**
  12822. * Create an uniform buffer
  12823. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12824. * @param elements defines the content of the uniform buffer
  12825. * @returns the webGL uniform buffer
  12826. */
  12827. Engine.prototype.createUniformBuffer = function (elements) {
  12828. var ubo = this._gl.createBuffer();
  12829. if (!ubo) {
  12830. throw new Error("Unable to create uniform buffer");
  12831. }
  12832. this.bindUniformBuffer(ubo);
  12833. if (elements instanceof Float32Array) {
  12834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12835. }
  12836. else {
  12837. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12838. }
  12839. this.bindUniformBuffer(null);
  12840. ubo.references = 1;
  12841. return ubo;
  12842. };
  12843. /**
  12844. * Create a dynamic uniform buffer
  12845. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12846. * @param elements defines the content of the uniform buffer
  12847. * @returns the webGL uniform buffer
  12848. */
  12849. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12850. var ubo = this._gl.createBuffer();
  12851. if (!ubo) {
  12852. throw new Error("Unable to create dynamic uniform buffer");
  12853. }
  12854. this.bindUniformBuffer(ubo);
  12855. if (elements instanceof Float32Array) {
  12856. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12857. }
  12858. else {
  12859. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12860. }
  12861. this.bindUniformBuffer(null);
  12862. ubo.references = 1;
  12863. return ubo;
  12864. };
  12865. /**
  12866. * Update an existing uniform buffer
  12867. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12868. * @param uniformBuffer defines the target uniform buffer
  12869. * @param elements defines the content to update
  12870. * @param offset defines the offset in the uniform buffer where update should start
  12871. * @param count defines the size of the data to update
  12872. */
  12873. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12874. this.bindUniformBuffer(uniformBuffer);
  12875. if (offset === undefined) {
  12876. offset = 0;
  12877. }
  12878. if (count === undefined) {
  12879. if (elements instanceof Float32Array) {
  12880. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12881. }
  12882. else {
  12883. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12884. }
  12885. }
  12886. else {
  12887. if (elements instanceof Float32Array) {
  12888. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12889. }
  12890. else {
  12891. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12892. }
  12893. }
  12894. this.bindUniformBuffer(null);
  12895. };
  12896. // VBOs
  12897. Engine.prototype._resetVertexBufferBinding = function () {
  12898. this.bindArrayBuffer(null);
  12899. this._cachedVertexBuffers = null;
  12900. };
  12901. /**
  12902. * Creates a vertex buffer
  12903. * @param data the data for the vertex buffer
  12904. * @returns the new WebGL static buffer
  12905. */
  12906. Engine.prototype.createVertexBuffer = function (data) {
  12907. var vbo = this._gl.createBuffer();
  12908. if (!vbo) {
  12909. throw new Error("Unable to create vertex buffer");
  12910. }
  12911. this.bindArrayBuffer(vbo);
  12912. if (data instanceof Array) {
  12913. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12914. }
  12915. else {
  12916. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12917. }
  12918. this._resetVertexBufferBinding();
  12919. vbo.references = 1;
  12920. return vbo;
  12921. };
  12922. /**
  12923. * Creates a dynamic vertex buffer
  12924. * @param data the data for the dynamic vertex buffer
  12925. * @returns the new WebGL dynamic buffer
  12926. */
  12927. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12928. var vbo = this._gl.createBuffer();
  12929. if (!vbo) {
  12930. throw new Error("Unable to create dynamic vertex buffer");
  12931. }
  12932. this.bindArrayBuffer(vbo);
  12933. if (data instanceof Array) {
  12934. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12935. }
  12936. else {
  12937. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12938. }
  12939. this._resetVertexBufferBinding();
  12940. vbo.references = 1;
  12941. return vbo;
  12942. };
  12943. /**
  12944. * Update a dynamic index buffer
  12945. * @param indexBuffer defines the target index buffer
  12946. * @param indices defines the data to update
  12947. * @param offset defines the offset in the target index buffer where update should start
  12948. */
  12949. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12950. if (offset === void 0) { offset = 0; }
  12951. // Force cache update
  12952. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12953. this.bindIndexBuffer(indexBuffer);
  12954. var arrayBuffer;
  12955. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12956. arrayBuffer = indices;
  12957. }
  12958. else {
  12959. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12960. }
  12961. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12962. this._resetIndexBufferBinding();
  12963. };
  12964. /**
  12965. * Updates a dynamic vertex buffer.
  12966. * @param vertexBuffer the vertex buffer to update
  12967. * @param data the data used to update the vertex buffer
  12968. * @param byteOffset the byte offset of the data
  12969. * @param byteLength the byte length of the data
  12970. */
  12971. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12972. this.bindArrayBuffer(vertexBuffer);
  12973. if (byteOffset === undefined) {
  12974. byteOffset = 0;
  12975. }
  12976. if (byteLength === undefined) {
  12977. if (data instanceof Array) {
  12978. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12979. }
  12980. else {
  12981. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12982. }
  12983. }
  12984. else {
  12985. if (data instanceof Array) {
  12986. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12987. }
  12988. else {
  12989. if (data instanceof ArrayBuffer) {
  12990. data = new Uint8Array(data, byteOffset, byteLength);
  12991. }
  12992. else {
  12993. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12994. }
  12995. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12996. }
  12997. }
  12998. this._resetVertexBufferBinding();
  12999. };
  13000. Engine.prototype._resetIndexBufferBinding = function () {
  13001. this.bindIndexBuffer(null);
  13002. this._cachedIndexBuffer = null;
  13003. };
  13004. /**
  13005. * Creates a new index buffer
  13006. * @param indices defines the content of the index buffer
  13007. * @param updatable defines if the index buffer must be updatable
  13008. * @returns a new webGL buffer
  13009. */
  13010. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13011. var vbo = this._gl.createBuffer();
  13012. if (!vbo) {
  13013. throw new Error("Unable to create index buffer");
  13014. }
  13015. this.bindIndexBuffer(vbo);
  13016. // Check for 32 bits indices
  13017. var arrayBuffer;
  13018. var need32Bits = false;
  13019. if (indices instanceof Uint16Array) {
  13020. arrayBuffer = indices;
  13021. }
  13022. else {
  13023. //check 32 bit support
  13024. if (this._caps.uintIndices) {
  13025. if (indices instanceof Uint32Array) {
  13026. arrayBuffer = indices;
  13027. need32Bits = true;
  13028. }
  13029. else {
  13030. //number[] or Int32Array, check if 32 bit is necessary
  13031. for (var index = 0; index < indices.length; index++) {
  13032. if (indices[index] > 65535) {
  13033. need32Bits = true;
  13034. break;
  13035. }
  13036. }
  13037. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13038. }
  13039. }
  13040. else {
  13041. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13042. arrayBuffer = new Uint16Array(indices);
  13043. }
  13044. }
  13045. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13046. this._resetIndexBufferBinding();
  13047. vbo.references = 1;
  13048. vbo.is32Bits = need32Bits;
  13049. return vbo;
  13050. };
  13051. /**
  13052. * Bind a webGL buffer to the webGL context
  13053. * @param buffer defines the buffer to bind
  13054. */
  13055. Engine.prototype.bindArrayBuffer = function (buffer) {
  13056. if (!this._vaoRecordInProgress) {
  13057. this._unbindVertexArrayObject();
  13058. }
  13059. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13060. };
  13061. /**
  13062. * Bind an uniform buffer to the current webGL context
  13063. * @param buffer defines the buffer to bind
  13064. */
  13065. Engine.prototype.bindUniformBuffer = function (buffer) {
  13066. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13067. };
  13068. /**
  13069. * Bind a buffer to the current webGL context at a given location
  13070. * @param buffer defines the buffer to bind
  13071. * @param location defines the index where to bind the buffer
  13072. */
  13073. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13074. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13075. };
  13076. /**
  13077. * Bind a specific block at a given index in a specific shader program
  13078. * @param shaderProgram defines the shader program
  13079. * @param blockName defines the block name
  13080. * @param index defines the index where to bind the block
  13081. */
  13082. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13083. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13084. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13085. };
  13086. ;
  13087. Engine.prototype.bindIndexBuffer = function (buffer) {
  13088. if (!this._vaoRecordInProgress) {
  13089. this._unbindVertexArrayObject();
  13090. }
  13091. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13092. };
  13093. Engine.prototype.bindBuffer = function (buffer, target) {
  13094. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13095. this._gl.bindBuffer(target, buffer);
  13096. this._currentBoundBuffer[target] = buffer;
  13097. }
  13098. };
  13099. /**
  13100. * update the bound buffer with the given data
  13101. * @param data defines the data to update
  13102. */
  13103. Engine.prototype.updateArrayBuffer = function (data) {
  13104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13105. };
  13106. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13107. var pointer = this._currentBufferPointers[indx];
  13108. var changed = false;
  13109. if (!pointer.active) {
  13110. changed = true;
  13111. pointer.active = true;
  13112. pointer.index = indx;
  13113. pointer.size = size;
  13114. pointer.type = type;
  13115. pointer.normalized = normalized;
  13116. pointer.stride = stride;
  13117. pointer.offset = offset;
  13118. pointer.buffer = buffer;
  13119. }
  13120. else {
  13121. if (pointer.buffer !== buffer) {
  13122. pointer.buffer = buffer;
  13123. changed = true;
  13124. }
  13125. if (pointer.size !== size) {
  13126. pointer.size = size;
  13127. changed = true;
  13128. }
  13129. if (pointer.type !== type) {
  13130. pointer.type = type;
  13131. changed = true;
  13132. }
  13133. if (pointer.normalized !== normalized) {
  13134. pointer.normalized = normalized;
  13135. changed = true;
  13136. }
  13137. if (pointer.stride !== stride) {
  13138. pointer.stride = stride;
  13139. changed = true;
  13140. }
  13141. if (pointer.offset !== offset) {
  13142. pointer.offset = offset;
  13143. changed = true;
  13144. }
  13145. }
  13146. if (changed || this._vaoRecordInProgress) {
  13147. this.bindArrayBuffer(buffer);
  13148. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13149. }
  13150. };
  13151. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13152. if (indexBuffer == null) {
  13153. return;
  13154. }
  13155. if (this._cachedIndexBuffer !== indexBuffer) {
  13156. this._cachedIndexBuffer = indexBuffer;
  13157. this.bindIndexBuffer(indexBuffer);
  13158. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13159. }
  13160. };
  13161. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13162. var attributes = effect.getAttributesNames();
  13163. if (!this._vaoRecordInProgress) {
  13164. this._unbindVertexArrayObject();
  13165. }
  13166. this.unbindAllAttributes();
  13167. for (var index = 0; index < attributes.length; index++) {
  13168. var order = effect.getAttributeLocation(index);
  13169. if (order >= 0) {
  13170. var vertexBuffer = vertexBuffers[attributes[index]];
  13171. if (!vertexBuffer) {
  13172. continue;
  13173. }
  13174. this._gl.enableVertexAttribArray(order);
  13175. if (!this._vaoRecordInProgress) {
  13176. this._vertexAttribArraysEnabled[order] = true;
  13177. }
  13178. var buffer = vertexBuffer.getBuffer();
  13179. if (buffer) {
  13180. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13181. if (vertexBuffer.getIsInstanced()) {
  13182. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13183. if (!this._vaoRecordInProgress) {
  13184. this._currentInstanceLocations.push(order);
  13185. this._currentInstanceBuffers.push(buffer);
  13186. }
  13187. }
  13188. }
  13189. }
  13190. }
  13191. };
  13192. /**
  13193. * Records a vertex array object
  13194. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13195. * @param vertexBuffers defines the list of vertex buffers to store
  13196. * @param indexBuffer defines the index buffer to store
  13197. * @param effect defines the effect to store
  13198. * @returns the new vertex array object
  13199. */
  13200. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13201. var vao = this._gl.createVertexArray();
  13202. this._vaoRecordInProgress = true;
  13203. this._gl.bindVertexArray(vao);
  13204. this._mustWipeVertexAttributes = true;
  13205. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13206. this.bindIndexBuffer(indexBuffer);
  13207. this._vaoRecordInProgress = false;
  13208. this._gl.bindVertexArray(null);
  13209. return vao;
  13210. };
  13211. /**
  13212. * Bind a specific vertex array object
  13213. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13214. * @param vertexArrayObject defines the vertex array object to bind
  13215. * @param indexBuffer defines the index buffer to bind
  13216. */
  13217. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13218. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13219. this._cachedVertexArrayObject = vertexArrayObject;
  13220. this._gl.bindVertexArray(vertexArrayObject);
  13221. this._cachedVertexBuffers = null;
  13222. this._cachedIndexBuffer = null;
  13223. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13224. this._mustWipeVertexAttributes = true;
  13225. }
  13226. };
  13227. /**
  13228. * Bind webGl buffers directly to the webGL context
  13229. * @param vertexBuffer defines the vertex buffer to bind
  13230. * @param indexBuffer defines the index buffer to bind
  13231. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13232. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13233. * @param effect defines the effect associated with the vertex buffer
  13234. */
  13235. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13236. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13237. this._cachedVertexBuffers = vertexBuffer;
  13238. this._cachedEffectForVertexBuffers = effect;
  13239. var attributesCount = effect.getAttributesCount();
  13240. this._unbindVertexArrayObject();
  13241. this.unbindAllAttributes();
  13242. var offset = 0;
  13243. for (var index = 0; index < attributesCount; index++) {
  13244. if (index < vertexDeclaration.length) {
  13245. var order = effect.getAttributeLocation(index);
  13246. if (order >= 0) {
  13247. this._gl.enableVertexAttribArray(order);
  13248. this._vertexAttribArraysEnabled[order] = true;
  13249. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13250. }
  13251. offset += vertexDeclaration[index] * 4;
  13252. }
  13253. }
  13254. }
  13255. this._bindIndexBufferWithCache(indexBuffer);
  13256. };
  13257. Engine.prototype._unbindVertexArrayObject = function () {
  13258. if (!this._cachedVertexArrayObject) {
  13259. return;
  13260. }
  13261. this._cachedVertexArrayObject = null;
  13262. this._gl.bindVertexArray(null);
  13263. };
  13264. /**
  13265. * Bind a list of vertex buffers to the webGL context
  13266. * @param vertexBuffers defines the list of vertex buffers to bind
  13267. * @param indexBuffer defines the index buffer to bind
  13268. * @param effect defines the effect associated with the vertex buffers
  13269. */
  13270. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13271. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13272. this._cachedVertexBuffers = vertexBuffers;
  13273. this._cachedEffectForVertexBuffers = effect;
  13274. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13275. }
  13276. this._bindIndexBufferWithCache(indexBuffer);
  13277. };
  13278. /**
  13279. * Unbind all instance attributes
  13280. */
  13281. Engine.prototype.unbindInstanceAttributes = function () {
  13282. var boundBuffer;
  13283. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13284. var instancesBuffer = this._currentInstanceBuffers[i];
  13285. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13286. boundBuffer = instancesBuffer;
  13287. this.bindArrayBuffer(instancesBuffer);
  13288. }
  13289. var offsetLocation = this._currentInstanceLocations[i];
  13290. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13291. }
  13292. this._currentInstanceBuffers.length = 0;
  13293. this._currentInstanceLocations.length = 0;
  13294. };
  13295. /**
  13296. * Release and free the memory of a vertex array object
  13297. * @param vao defines the vertex array object to delete
  13298. */
  13299. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13300. this._gl.deleteVertexArray(vao);
  13301. };
  13302. /** @hidden */
  13303. Engine.prototype._releaseBuffer = function (buffer) {
  13304. buffer.references--;
  13305. if (buffer.references === 0) {
  13306. this._gl.deleteBuffer(buffer);
  13307. return true;
  13308. }
  13309. return false;
  13310. };
  13311. /**
  13312. * Creates a webGL buffer to use with instanciation
  13313. * @param capacity defines the size of the buffer
  13314. * @returns the webGL buffer
  13315. */
  13316. Engine.prototype.createInstancesBuffer = function (capacity) {
  13317. var buffer = this._gl.createBuffer();
  13318. if (!buffer) {
  13319. throw new Error("Unable to create instance buffer");
  13320. }
  13321. buffer.capacity = capacity;
  13322. this.bindArrayBuffer(buffer);
  13323. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13324. return buffer;
  13325. };
  13326. /**
  13327. * Delete a webGL buffer used with instanciation
  13328. * @param buffer defines the webGL buffer to delete
  13329. */
  13330. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13331. this._gl.deleteBuffer(buffer);
  13332. };
  13333. /**
  13334. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13335. * @param instancesBuffer defines the webGL buffer to update and bind
  13336. * @param data defines the data to store in the buffer
  13337. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13338. */
  13339. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13340. this.bindArrayBuffer(instancesBuffer);
  13341. if (data) {
  13342. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13343. }
  13344. if (offsetLocations[0].index !== undefined) {
  13345. var stride = 0;
  13346. for (var i = 0; i < offsetLocations.length; i++) {
  13347. var ai = offsetLocations[i];
  13348. stride += ai.attributeSize * 4;
  13349. }
  13350. for (var i = 0; i < offsetLocations.length; i++) {
  13351. var ai = offsetLocations[i];
  13352. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13353. this._gl.enableVertexAttribArray(ai.index);
  13354. this._vertexAttribArraysEnabled[ai.index] = true;
  13355. }
  13356. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13357. this._gl.vertexAttribDivisor(ai.index, 1);
  13358. this._currentInstanceLocations.push(ai.index);
  13359. this._currentInstanceBuffers.push(instancesBuffer);
  13360. }
  13361. }
  13362. else {
  13363. for (var index = 0; index < 4; index++) {
  13364. var offsetLocation = offsetLocations[index];
  13365. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13366. this._gl.enableVertexAttribArray(offsetLocation);
  13367. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13368. }
  13369. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13370. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13371. this._currentInstanceLocations.push(offsetLocation);
  13372. this._currentInstanceBuffers.push(instancesBuffer);
  13373. }
  13374. }
  13375. };
  13376. /**
  13377. * Apply all cached states (depth, culling, stencil and alpha)
  13378. */
  13379. Engine.prototype.applyStates = function () {
  13380. this._depthCullingState.apply(this._gl);
  13381. this._stencilState.apply(this._gl);
  13382. this._alphaState.apply(this._gl);
  13383. };
  13384. /**
  13385. * Send a draw order
  13386. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13387. * @param indexStart defines the starting index
  13388. * @param indexCount defines the number of index to draw
  13389. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13390. */
  13391. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13392. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13393. };
  13394. /**
  13395. * Draw a list of points
  13396. * @param verticesStart defines the index of first vertex to draw
  13397. * @param verticesCount defines the count of vertices to draw
  13398. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13399. */
  13400. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13401. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13402. };
  13403. /**
  13404. * Draw a list of unindexed primitives
  13405. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13406. * @param verticesStart defines the index of first vertex to draw
  13407. * @param verticesCount defines the count of vertices to draw
  13408. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13409. */
  13410. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13411. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13412. };
  13413. /**
  13414. * Draw a list of indexed primitives
  13415. * @param fillMode defines the primitive to use
  13416. * @param indexStart defines the starting index
  13417. * @param indexCount defines the number of index to draw
  13418. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13419. */
  13420. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13421. // Apply states
  13422. this.applyStates();
  13423. this._drawCalls.addCount(1, false);
  13424. // Render
  13425. var drawMode = this._drawMode(fillMode);
  13426. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13427. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13428. if (instancesCount) {
  13429. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13430. }
  13431. else {
  13432. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13433. }
  13434. };
  13435. /**
  13436. * Draw a list of unindexed primitives
  13437. * @param fillMode defines the primitive to use
  13438. * @param verticesStart defines the index of first vertex to draw
  13439. * @param verticesCount defines the count of vertices to draw
  13440. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13441. */
  13442. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13443. // Apply states
  13444. this.applyStates();
  13445. this._drawCalls.addCount(1, false);
  13446. var drawMode = this._drawMode(fillMode);
  13447. if (instancesCount) {
  13448. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13449. }
  13450. else {
  13451. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13452. }
  13453. };
  13454. Engine.prototype._drawMode = function (fillMode) {
  13455. switch (fillMode) {
  13456. // Triangle views
  13457. case BABYLON.Material.TriangleFillMode:
  13458. return this._gl.TRIANGLES;
  13459. case BABYLON.Material.PointFillMode:
  13460. return this._gl.POINTS;
  13461. case BABYLON.Material.WireFrameFillMode:
  13462. return this._gl.LINES;
  13463. // Draw modes
  13464. case BABYLON.Material.PointListDrawMode:
  13465. return this._gl.POINTS;
  13466. case BABYLON.Material.LineListDrawMode:
  13467. return this._gl.LINES;
  13468. case BABYLON.Material.LineLoopDrawMode:
  13469. return this._gl.LINE_LOOP;
  13470. case BABYLON.Material.LineStripDrawMode:
  13471. return this._gl.LINE_STRIP;
  13472. case BABYLON.Material.TriangleStripDrawMode:
  13473. return this._gl.TRIANGLE_STRIP;
  13474. case BABYLON.Material.TriangleFanDrawMode:
  13475. return this._gl.TRIANGLE_FAN;
  13476. default:
  13477. return this._gl.TRIANGLES;
  13478. }
  13479. };
  13480. // Shaders
  13481. /** @hidden */
  13482. Engine.prototype._releaseEffect = function (effect) {
  13483. if (this._compiledEffects[effect._key]) {
  13484. delete this._compiledEffects[effect._key];
  13485. this._deleteProgram(effect.getProgram());
  13486. }
  13487. };
  13488. /** @hidden */
  13489. Engine.prototype._deleteProgram = function (program) {
  13490. if (program) {
  13491. program.__SPECTOR_rebuildProgram = null;
  13492. if (program.transformFeedback) {
  13493. this.deleteTransformFeedback(program.transformFeedback);
  13494. program.transformFeedback = null;
  13495. }
  13496. this._gl.deleteProgram(program);
  13497. }
  13498. };
  13499. /**
  13500. * Create a new effect (used to store vertex/fragment shaders)
  13501. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13502. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13503. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13504. * @param samplers defines an array of string used to represent textures
  13505. * @param defines defines the string containing the defines to use to compile the shaders
  13506. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13507. * @param onCompiled defines a function to call when the effect creation is successful
  13508. * @param onError defines a function to call when the effect creation has failed
  13509. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13510. * @returns the new Effect
  13511. */
  13512. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13513. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13514. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13515. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13516. if (this._compiledEffects[name]) {
  13517. var compiledEffect = this._compiledEffects[name];
  13518. if (onCompiled && compiledEffect.isReady()) {
  13519. onCompiled(compiledEffect);
  13520. }
  13521. return compiledEffect;
  13522. }
  13523. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13524. effect._key = name;
  13525. this._compiledEffects[name] = effect;
  13526. return effect;
  13527. };
  13528. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13529. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13530. };
  13531. ;
  13532. Engine.prototype._compileRawShader = function (source, type) {
  13533. var gl = this._gl;
  13534. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13535. gl.shaderSource(shader, source);
  13536. gl.compileShader(shader);
  13537. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13538. var log = gl.getShaderInfoLog(shader);
  13539. if (log) {
  13540. throw new Error(log);
  13541. }
  13542. }
  13543. if (!shader) {
  13544. throw new Error("Something went wrong while compile the shader.");
  13545. }
  13546. return shader;
  13547. };
  13548. ;
  13549. /**
  13550. * Directly creates a webGL program
  13551. * @param vertexCode defines the vertex shader code to use
  13552. * @param fragmentCode defines the fragment shader code to use
  13553. * @param context defines the webGL context to use (if not set, the current one will be used)
  13554. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13555. * @returns the new webGL program
  13556. */
  13557. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13558. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13559. context = context || this._gl;
  13560. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13561. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13562. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13563. };
  13564. /**
  13565. * Creates a webGL program
  13566. * @param vertexCode defines the vertex shader code to use
  13567. * @param fragmentCode defines the fragment shader code to use
  13568. * @param defines defines the string containing the defines to use to compile the shaders
  13569. * @param context defines the webGL context to use (if not set, the current one will be used)
  13570. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13571. * @returns the new webGL program
  13572. */
  13573. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13574. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13575. context = context || this._gl;
  13576. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13577. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13578. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13579. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13580. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13581. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13582. return program;
  13583. };
  13584. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13585. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13586. var shaderProgram = context.createProgram();
  13587. if (!shaderProgram) {
  13588. throw new Error("Unable to create program");
  13589. }
  13590. context.attachShader(shaderProgram, vertexShader);
  13591. context.attachShader(shaderProgram, fragmentShader);
  13592. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13593. var transformFeedback = this.createTransformFeedback();
  13594. this.bindTransformFeedback(transformFeedback);
  13595. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13596. shaderProgram.transformFeedback = transformFeedback;
  13597. }
  13598. context.linkProgram(shaderProgram);
  13599. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13600. this.bindTransformFeedback(null);
  13601. }
  13602. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13603. if (!linked) {
  13604. var error = context.getProgramInfoLog(shaderProgram);
  13605. if (error) {
  13606. throw new Error(error);
  13607. }
  13608. }
  13609. if (this.validateShaderPrograms) {
  13610. context.validateProgram(shaderProgram);
  13611. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13612. if (!validated) {
  13613. var error = context.getProgramInfoLog(shaderProgram);
  13614. if (error) {
  13615. throw new Error(error);
  13616. }
  13617. }
  13618. }
  13619. context.deleteShader(vertexShader);
  13620. context.deleteShader(fragmentShader);
  13621. return shaderProgram;
  13622. };
  13623. /**
  13624. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13625. * @param shaderProgram defines the webGL program to use
  13626. * @param uniformsNames defines the list of uniform names
  13627. * @returns an array of webGL uniform locations
  13628. */
  13629. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13630. var results = new Array();
  13631. for (var index = 0; index < uniformsNames.length; index++) {
  13632. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13633. }
  13634. return results;
  13635. };
  13636. /**
  13637. * Gets the lsit of active attributes for a given webGL program
  13638. * @param shaderProgram defines the webGL program to use
  13639. * @param attributesNames defines the list of attribute names to get
  13640. * @returns an array of indices indicating the offset of each attribute
  13641. */
  13642. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13643. var results = [];
  13644. for (var index = 0; index < attributesNames.length; index++) {
  13645. try {
  13646. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13647. }
  13648. catch (e) {
  13649. results.push(-1);
  13650. }
  13651. }
  13652. return results;
  13653. };
  13654. /**
  13655. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13656. * @param effect defines the effect to activate
  13657. */
  13658. Engine.prototype.enableEffect = function (effect) {
  13659. if (!effect) {
  13660. return;
  13661. }
  13662. // Use program
  13663. this.bindSamplers(effect);
  13664. this._currentEffect = effect;
  13665. if (effect.onBind) {
  13666. effect.onBind(effect);
  13667. }
  13668. effect.onBindObservable.notifyObservers(effect);
  13669. };
  13670. /**
  13671. * Set the value of an uniform to an array of int32
  13672. * @param uniform defines the webGL uniform location where to store the value
  13673. * @param array defines the array of int32 to store
  13674. */
  13675. Engine.prototype.setIntArray = function (uniform, array) {
  13676. if (!uniform)
  13677. return;
  13678. this._gl.uniform1iv(uniform, array);
  13679. };
  13680. /**
  13681. * Set the value of an uniform to an array of int32 (stored as vec2)
  13682. * @param uniform defines the webGL uniform location where to store the value
  13683. * @param array defines the array of int32 to store
  13684. */
  13685. Engine.prototype.setIntArray2 = function (uniform, array) {
  13686. if (!uniform || array.length % 2 !== 0)
  13687. return;
  13688. this._gl.uniform2iv(uniform, array);
  13689. };
  13690. /**
  13691. * Set the value of an uniform to an array of int32 (stored as vec3)
  13692. * @param uniform defines the webGL uniform location where to store the value
  13693. * @param array defines the array of int32 to store
  13694. */
  13695. Engine.prototype.setIntArray3 = function (uniform, array) {
  13696. if (!uniform || array.length % 3 !== 0)
  13697. return;
  13698. this._gl.uniform3iv(uniform, array);
  13699. };
  13700. /**
  13701. * Set the value of an uniform to an array of int32 (stored as vec4)
  13702. * @param uniform defines the webGL uniform location where to store the value
  13703. * @param array defines the array of int32 to store
  13704. */
  13705. Engine.prototype.setIntArray4 = function (uniform, array) {
  13706. if (!uniform || array.length % 4 !== 0)
  13707. return;
  13708. this._gl.uniform4iv(uniform, array);
  13709. };
  13710. /**
  13711. * Set the value of an uniform to an array of float32
  13712. * @param uniform defines the webGL uniform location where to store the value
  13713. * @param array defines the array of float32 to store
  13714. */
  13715. Engine.prototype.setFloatArray = function (uniform, array) {
  13716. if (!uniform)
  13717. return;
  13718. this._gl.uniform1fv(uniform, array);
  13719. };
  13720. /**
  13721. * Set the value of an uniform to an array of float32 (stored as vec2)
  13722. * @param uniform defines the webGL uniform location where to store the value
  13723. * @param array defines the array of float32 to store
  13724. */
  13725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13726. if (!uniform || array.length % 2 !== 0)
  13727. return;
  13728. this._gl.uniform2fv(uniform, array);
  13729. };
  13730. /**
  13731. * Set the value of an uniform to an array of float32 (stored as vec3)
  13732. * @param uniform defines the webGL uniform location where to store the value
  13733. * @param array defines the array of float32 to store
  13734. */
  13735. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13736. if (!uniform || array.length % 3 !== 0)
  13737. return;
  13738. this._gl.uniform3fv(uniform, array);
  13739. };
  13740. /**
  13741. * Set the value of an uniform to an array of float32 (stored as vec4)
  13742. * @param uniform defines the webGL uniform location where to store the value
  13743. * @param array defines the array of float32 to store
  13744. */
  13745. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13746. if (!uniform || array.length % 4 !== 0)
  13747. return;
  13748. this._gl.uniform4fv(uniform, array);
  13749. };
  13750. /**
  13751. * Set the value of an uniform to an array of number
  13752. * @param uniform defines the webGL uniform location where to store the value
  13753. * @param array defines the array of number to store
  13754. */
  13755. Engine.prototype.setArray = function (uniform, array) {
  13756. if (!uniform)
  13757. return;
  13758. this._gl.uniform1fv(uniform, array);
  13759. };
  13760. /**
  13761. * Set the value of an uniform to an array of number (stored as vec2)
  13762. * @param uniform defines the webGL uniform location where to store the value
  13763. * @param array defines the array of number to store
  13764. */
  13765. Engine.prototype.setArray2 = function (uniform, array) {
  13766. if (!uniform || array.length % 2 !== 0)
  13767. return;
  13768. this._gl.uniform2fv(uniform, array);
  13769. };
  13770. /**
  13771. * Set the value of an uniform to an array of number (stored as vec3)
  13772. * @param uniform defines the webGL uniform location where to store the value
  13773. * @param array defines the array of number to store
  13774. */
  13775. Engine.prototype.setArray3 = function (uniform, array) {
  13776. if (!uniform || array.length % 3 !== 0)
  13777. return;
  13778. this._gl.uniform3fv(uniform, array);
  13779. };
  13780. /**
  13781. * Set the value of an uniform to an array of number (stored as vec4)
  13782. * @param uniform defines the webGL uniform location where to store the value
  13783. * @param array defines the array of number to store
  13784. */
  13785. Engine.prototype.setArray4 = function (uniform, array) {
  13786. if (!uniform || array.length % 4 !== 0)
  13787. return;
  13788. this._gl.uniform4fv(uniform, array);
  13789. };
  13790. /**
  13791. * Set the value of an uniform to an array of float32 (stored as matrices)
  13792. * @param uniform defines the webGL uniform location where to store the value
  13793. * @param matrices defines the array of float32 to store
  13794. */
  13795. Engine.prototype.setMatrices = function (uniform, matrices) {
  13796. if (!uniform)
  13797. return;
  13798. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13799. };
  13800. /**
  13801. * Set the value of an uniform to a matrix
  13802. * @param uniform defines the webGL uniform location where to store the value
  13803. * @param matrix defines the matrix to store
  13804. */
  13805. Engine.prototype.setMatrix = function (uniform, matrix) {
  13806. if (!uniform)
  13807. return;
  13808. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13809. };
  13810. /**
  13811. * Set the value of an uniform to a matrix (3x3)
  13812. * @param uniform defines the webGL uniform location where to store the value
  13813. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13814. */
  13815. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13816. if (!uniform)
  13817. return;
  13818. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13819. };
  13820. /**
  13821. * Set the value of an uniform to a matrix (2x2)
  13822. * @param uniform defines the webGL uniform location where to store the value
  13823. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13824. */
  13825. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13826. if (!uniform)
  13827. return;
  13828. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13829. };
  13830. /**
  13831. * Set the value of an uniform to a number (int)
  13832. * @param uniform defines the webGL uniform location where to store the value
  13833. * @param value defines the int number to store
  13834. */
  13835. Engine.prototype.setInt = function (uniform, value) {
  13836. if (!uniform)
  13837. return;
  13838. this._gl.uniform1i(uniform, value);
  13839. };
  13840. /**
  13841. * Set the value of an uniform to a number (float)
  13842. * @param uniform defines the webGL uniform location where to store the value
  13843. * @param value defines the float number to store
  13844. */
  13845. Engine.prototype.setFloat = function (uniform, value) {
  13846. if (!uniform)
  13847. return;
  13848. this._gl.uniform1f(uniform, value);
  13849. };
  13850. /**
  13851. * Set the value of an uniform to a vec2
  13852. * @param uniform defines the webGL uniform location where to store the value
  13853. * @param x defines the 1st component of the value
  13854. * @param y defines the 2nd component of the value
  13855. */
  13856. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13857. if (!uniform)
  13858. return;
  13859. this._gl.uniform2f(uniform, x, y);
  13860. };
  13861. /**
  13862. * Set the value of an uniform to a vec3
  13863. * @param uniform defines the webGL uniform location where to store the value
  13864. * @param x defines the 1st component of the value
  13865. * @param y defines the 2nd component of the value
  13866. * @param z defines the 3rd component of the value
  13867. */
  13868. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13869. if (!uniform)
  13870. return;
  13871. this._gl.uniform3f(uniform, x, y, z);
  13872. };
  13873. /**
  13874. * Set the value of an uniform to a boolean
  13875. * @param uniform defines the webGL uniform location where to store the value
  13876. * @param bool defines the boolean to store
  13877. */
  13878. Engine.prototype.setBool = function (uniform, bool) {
  13879. if (!uniform)
  13880. return;
  13881. this._gl.uniform1i(uniform, bool);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to a vec4
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param x defines the 1st component of the value
  13887. * @param y defines the 2nd component of the value
  13888. * @param z defines the 3rd component of the value
  13889. * @param w defines the 4th component of the value
  13890. */
  13891. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniform4f(uniform, x, y, z, w);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a Color3
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param color3 defines the color to store
  13900. */
  13901. Engine.prototype.setColor3 = function (uniform, color3) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a Color3 and an alpha value
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param color3 defines the color to store
  13910. * @param alpha defines the alpha component to store
  13911. */
  13912. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13913. if (!uniform)
  13914. return;
  13915. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13916. };
  13917. /**
  13918. * Sets a Color4 on a uniform variable
  13919. * @param uniform defines the uniform location
  13920. * @param color4 defines the value to be set
  13921. */
  13922. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13923. if (!uniform)
  13924. return;
  13925. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13926. };
  13927. // States
  13928. /**
  13929. * Set various states to the webGL context
  13930. * @param culling defines backface culling state
  13931. * @param zOffset defines the value to apply to zOffset (0 by default)
  13932. * @param force defines if states must be applied even if cache is up to date
  13933. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13934. */
  13935. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13936. if (zOffset === void 0) { zOffset = 0; }
  13937. if (reverseSide === void 0) { reverseSide = false; }
  13938. // Culling
  13939. if (this._depthCullingState.cull !== culling || force) {
  13940. this._depthCullingState.cull = culling;
  13941. }
  13942. // Cull face
  13943. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13944. if (this._depthCullingState.cullFace !== cullFace || force) {
  13945. this._depthCullingState.cullFace = cullFace;
  13946. }
  13947. // Z offset
  13948. this.setZOffset(zOffset);
  13949. // Front face
  13950. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13951. if (this._depthCullingState.frontFace !== frontFace || force) {
  13952. this._depthCullingState.frontFace = frontFace;
  13953. }
  13954. };
  13955. /**
  13956. * Set the z offset to apply to current rendering
  13957. * @param value defines the offset to apply
  13958. */
  13959. Engine.prototype.setZOffset = function (value) {
  13960. this._depthCullingState.zOffset = value;
  13961. };
  13962. /**
  13963. * Gets the current value of the zOffset
  13964. * @returns the current zOffset state
  13965. */
  13966. Engine.prototype.getZOffset = function () {
  13967. return this._depthCullingState.zOffset;
  13968. };
  13969. /**
  13970. * Enable or disable depth buffering
  13971. * @param enable defines the state to set
  13972. */
  13973. Engine.prototype.setDepthBuffer = function (enable) {
  13974. this._depthCullingState.depthTest = enable;
  13975. };
  13976. /**
  13977. * Gets a boolean indicating if depth writing is enabled
  13978. * @returns the current depth writing state
  13979. */
  13980. Engine.prototype.getDepthWrite = function () {
  13981. return this._depthCullingState.depthMask;
  13982. };
  13983. /**
  13984. * Enable or disable depth writing
  13985. * @param enable defines the state to set
  13986. */
  13987. Engine.prototype.setDepthWrite = function (enable) {
  13988. this._depthCullingState.depthMask = enable;
  13989. };
  13990. /**
  13991. * Enable or disable color writing
  13992. * @param enable defines the state to set
  13993. */
  13994. Engine.prototype.setColorWrite = function (enable) {
  13995. this._gl.colorMask(enable, enable, enable, enable);
  13996. this._colorWrite = enable;
  13997. };
  13998. /**
  13999. * Gets a boolean indicating if color writing is enabled
  14000. * @returns the current color writing state
  14001. */
  14002. Engine.prototype.getColorWrite = function () {
  14003. return this._colorWrite;
  14004. };
  14005. /**
  14006. * Sets alpha constants used by some alpha blending modes
  14007. * @param r defines the red component
  14008. * @param g defines the green component
  14009. * @param b defines the blue component
  14010. * @param a defines the alpha component
  14011. */
  14012. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14013. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14014. };
  14015. /**
  14016. * Sets the current alpha mode
  14017. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14018. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14019. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14020. */
  14021. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14022. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14023. if (this._alphaMode === mode) {
  14024. return;
  14025. }
  14026. switch (mode) {
  14027. case Engine.ALPHA_DISABLE:
  14028. this._alphaState.alphaBlend = false;
  14029. break;
  14030. case Engine.ALPHA_PREMULTIPLIED:
  14031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14032. this._alphaState.alphaBlend = true;
  14033. break;
  14034. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14036. this._alphaState.alphaBlend = true;
  14037. break;
  14038. case Engine.ALPHA_COMBINE:
  14039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14040. this._alphaState.alphaBlend = true;
  14041. break;
  14042. case Engine.ALPHA_ONEONE:
  14043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14044. this._alphaState.alphaBlend = true;
  14045. break;
  14046. case Engine.ALPHA_ADD:
  14047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14048. this._alphaState.alphaBlend = true;
  14049. break;
  14050. case Engine.ALPHA_SUBTRACT:
  14051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14052. this._alphaState.alphaBlend = true;
  14053. break;
  14054. case Engine.ALPHA_MULTIPLY:
  14055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14056. this._alphaState.alphaBlend = true;
  14057. break;
  14058. case Engine.ALPHA_MAXIMIZED:
  14059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14060. this._alphaState.alphaBlend = true;
  14061. break;
  14062. case Engine.ALPHA_INTERPOLATE:
  14063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14064. this._alphaState.alphaBlend = true;
  14065. break;
  14066. case Engine.ALPHA_SCREENMODE:
  14067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14068. this._alphaState.alphaBlend = true;
  14069. break;
  14070. }
  14071. if (!noDepthWriteChange) {
  14072. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14073. }
  14074. this._alphaMode = mode;
  14075. };
  14076. /**
  14077. * Gets the current alpha mode
  14078. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14079. * @returns the current alpha mode
  14080. */
  14081. Engine.prototype.getAlphaMode = function () {
  14082. return this._alphaMode;
  14083. };
  14084. // Textures
  14085. /**
  14086. * Clears the list of texture accessible through engine.
  14087. * This can help preventing texture load conflict due to name collision.
  14088. */
  14089. Engine.prototype.clearInternalTexturesCache = function () {
  14090. this._internalTexturesCache = [];
  14091. };
  14092. /**
  14093. * Force the entire cache to be cleared
  14094. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14095. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14096. */
  14097. Engine.prototype.wipeCaches = function (bruteForce) {
  14098. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14099. return;
  14100. }
  14101. this._currentEffect = null;
  14102. this._unpackFlipYCached = null;
  14103. this._viewportCached.x = 0;
  14104. this._viewportCached.y = 0;
  14105. this._viewportCached.z = 0;
  14106. this._viewportCached.w = 0;
  14107. if (bruteForce) {
  14108. this.resetTextureCache();
  14109. this._currentProgram = null;
  14110. this._stencilState.reset();
  14111. this._depthCullingState.reset();
  14112. this.setDepthFunctionToLessOrEqual();
  14113. this._alphaState.reset();
  14114. }
  14115. this._resetVertexBufferBinding();
  14116. this._cachedIndexBuffer = null;
  14117. this._cachedEffectForVertexBuffers = null;
  14118. this._unbindVertexArrayObject();
  14119. this.bindIndexBuffer(null);
  14120. };
  14121. /**
  14122. * Set the compressed texture format to use, based on the formats you have, and the formats
  14123. * supported by the hardware / browser.
  14124. *
  14125. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14126. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14127. * to API arguments needed to compressed textures. This puts the burden on the container
  14128. * generator to house the arcane code for determining these for current & future formats.
  14129. *
  14130. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14131. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14132. *
  14133. * Note: The result of this call is not taken into account when a texture is base64.
  14134. *
  14135. * @param formatsAvailable defines the list of those format families you have created
  14136. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14137. *
  14138. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14139. * @returns The extension selected.
  14140. */
  14141. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14142. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14143. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14144. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14145. return this._textureFormatInUse = this._texturesSupported[i];
  14146. }
  14147. }
  14148. }
  14149. // actively set format to nothing, to allow this to be called more than once
  14150. // and possibly fail the 2nd time
  14151. this._textureFormatInUse = null;
  14152. return null;
  14153. };
  14154. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14155. var gl = this._gl;
  14156. var magFilter = gl.NEAREST;
  14157. var minFilter = gl.NEAREST;
  14158. switch (samplingMode) {
  14159. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14160. magFilter = gl.LINEAR;
  14161. if (generateMipMaps) {
  14162. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14163. }
  14164. else {
  14165. minFilter = gl.LINEAR;
  14166. }
  14167. break;
  14168. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14169. magFilter = gl.LINEAR;
  14170. if (generateMipMaps) {
  14171. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14172. }
  14173. else {
  14174. minFilter = gl.LINEAR;
  14175. }
  14176. break;
  14177. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14178. magFilter = gl.NEAREST;
  14179. if (generateMipMaps) {
  14180. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14181. }
  14182. else {
  14183. minFilter = gl.NEAREST;
  14184. }
  14185. break;
  14186. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14187. magFilter = gl.NEAREST;
  14188. if (generateMipMaps) {
  14189. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14190. }
  14191. else {
  14192. minFilter = gl.NEAREST;
  14193. }
  14194. break;
  14195. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14196. magFilter = gl.NEAREST;
  14197. if (generateMipMaps) {
  14198. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14199. }
  14200. else {
  14201. minFilter = gl.LINEAR;
  14202. }
  14203. break;
  14204. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14205. magFilter = gl.NEAREST;
  14206. if (generateMipMaps) {
  14207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14208. }
  14209. else {
  14210. minFilter = gl.LINEAR;
  14211. }
  14212. break;
  14213. case Engine.TEXTURE_NEAREST_LINEAR:
  14214. magFilter = gl.NEAREST;
  14215. minFilter = gl.LINEAR;
  14216. break;
  14217. case Engine.TEXTURE_NEAREST_NEAREST:
  14218. magFilter = gl.NEAREST;
  14219. minFilter = gl.NEAREST;
  14220. break;
  14221. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14222. magFilter = gl.LINEAR;
  14223. if (generateMipMaps) {
  14224. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14225. }
  14226. else {
  14227. minFilter = gl.NEAREST;
  14228. }
  14229. break;
  14230. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14231. magFilter = gl.LINEAR;
  14232. if (generateMipMaps) {
  14233. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14234. }
  14235. else {
  14236. minFilter = gl.NEAREST;
  14237. }
  14238. break;
  14239. case Engine.TEXTURE_LINEAR_LINEAR:
  14240. magFilter = gl.LINEAR;
  14241. minFilter = gl.LINEAR;
  14242. break;
  14243. case Engine.TEXTURE_LINEAR_NEAREST:
  14244. magFilter = gl.LINEAR;
  14245. minFilter = gl.NEAREST;
  14246. break;
  14247. }
  14248. return {
  14249. min: minFilter,
  14250. mag: magFilter
  14251. };
  14252. };
  14253. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14254. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14255. var img;
  14256. var onload = function () {
  14257. loadedImages[index] = img;
  14258. loadedImages._internalCount++;
  14259. if (scene) {
  14260. scene._removePendingData(img);
  14261. }
  14262. if (loadedImages._internalCount === 6) {
  14263. onfinish(loadedImages);
  14264. }
  14265. };
  14266. var onerror = function (message, exception) {
  14267. if (scene) {
  14268. scene._removePendingData(img);
  14269. }
  14270. if (onErrorCallBack) {
  14271. onErrorCallBack(message, exception);
  14272. }
  14273. };
  14274. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14275. if (scene) {
  14276. scene._addPendingData(img);
  14277. }
  14278. };
  14279. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14280. if (onError === void 0) { onError = null; }
  14281. var loadedImages = [];
  14282. loadedImages._internalCount = 0;
  14283. for (var index = 0; index < 6; index++) {
  14284. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14285. }
  14286. };
  14287. ;
  14288. /** @hidden */
  14289. Engine.prototype._createTexture = function () {
  14290. var texture = this._gl.createTexture();
  14291. if (!texture) {
  14292. throw new Error("Unable to create texture");
  14293. }
  14294. return texture;
  14295. };
  14296. /**
  14297. * Usually called from BABYLON.Texture.ts.
  14298. * Passed information to create a WebGLTexture
  14299. * @param urlArg defines a value which contains one of the following:
  14300. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14301. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14302. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14303. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14304. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14305. * @param scene needed for loading to the correct scene
  14306. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14307. * @param onLoad optional callback to be called upon successful completion
  14308. * @param onError optional callback to be called upon failure
  14309. * @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
  14310. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14311. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14312. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14313. */
  14314. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14315. var _this = this;
  14316. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14317. if (onLoad === void 0) { onLoad = null; }
  14318. if (onError === void 0) { onError = null; }
  14319. if (buffer === void 0) { buffer = null; }
  14320. if (fallback === void 0) { fallback = null; }
  14321. if (format === void 0) { format = null; }
  14322. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14323. var fromData = url.substr(0, 5) === "data:";
  14324. var fromBlob = url.substr(0, 5) === "blob:";
  14325. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14326. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14327. // establish the file extension, if possible
  14328. var lastDot = url.lastIndexOf('.');
  14329. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14330. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14331. var isTGA = (extension.indexOf(".tga") === 0);
  14332. // determine if a ktx file should be substituted
  14333. var isKTX = false;
  14334. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14335. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14336. isKTX = true;
  14337. }
  14338. if (scene) {
  14339. scene._addPendingData(texture);
  14340. }
  14341. texture.url = url;
  14342. texture.generateMipMaps = !noMipmap;
  14343. texture.samplingMode = samplingMode;
  14344. texture.invertY = invertY;
  14345. if (!this._doNotHandleContextLost) {
  14346. // Keep a link to the buffer only if we plan to handle context lost
  14347. texture._buffer = buffer;
  14348. }
  14349. var onLoadObserver = null;
  14350. if (onLoad && !fallback) {
  14351. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14352. }
  14353. if (!fallback)
  14354. this._internalTexturesCache.push(texture);
  14355. var onerror = function (message, exception) {
  14356. if (scene) {
  14357. scene._removePendingData(texture);
  14358. }
  14359. if (onLoadObserver && !isKTX) {
  14360. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14361. texture.onLoadedObservable.remove(onLoadObserver);
  14362. }
  14363. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14364. if (isKTX) {
  14365. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14366. }
  14367. else if (BABYLON.Tools.UseFallbackTexture) {
  14368. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14369. }
  14370. if (onError) {
  14371. onError(message || "Unknown error", exception);
  14372. }
  14373. };
  14374. var callback = null;
  14375. // processing for non-image formats
  14376. if (isKTX || isTGA || isDDS) {
  14377. if (isKTX) {
  14378. callback = function (data) {
  14379. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14380. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14381. ktx.uploadLevels(texture, !noMipmap);
  14382. return false;
  14383. }, samplingMode);
  14384. };
  14385. }
  14386. else if (isTGA) {
  14387. callback = function (arrayBuffer) {
  14388. var data = new Uint8Array(arrayBuffer);
  14389. var header = BABYLON.TGATools.GetTGAHeader(data);
  14390. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14391. BABYLON.TGATools.UploadContent(texture, data);
  14392. return false;
  14393. }, samplingMode);
  14394. };
  14395. }
  14396. else if (isDDS) {
  14397. callback = function (data) {
  14398. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14399. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14400. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14401. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14402. return false;
  14403. }, samplingMode);
  14404. };
  14405. }
  14406. if (!buffer) {
  14407. this._loadFile(url, function (data) {
  14408. if (callback) {
  14409. callback(data);
  14410. }
  14411. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14412. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14413. });
  14414. }
  14415. else {
  14416. if (callback) {
  14417. callback(buffer);
  14418. }
  14419. }
  14420. // image format processing
  14421. }
  14422. else {
  14423. var onload = function (img) {
  14424. if (fromBlob && !_this._doNotHandleContextLost) {
  14425. // We need to store the image if we need to rebuild the texture
  14426. // in case of a webgl context lost
  14427. texture._buffer = img;
  14428. }
  14429. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14430. var gl = _this._gl;
  14431. var isPot = (img.width === potWidth && img.height === potHeight);
  14432. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14433. if (isPot) {
  14434. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14435. return false;
  14436. }
  14437. var maxTextureSize = _this._caps.maxTextureSize;
  14438. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14439. _this._prepareWorkingCanvas();
  14440. if (!_this._workingCanvas || !_this._workingContext) {
  14441. return false;
  14442. }
  14443. _this._workingCanvas.width = potWidth;
  14444. _this._workingCanvas.height = potHeight;
  14445. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14446. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14447. texture.width = potWidth;
  14448. texture.height = potHeight;
  14449. return false;
  14450. }
  14451. else {
  14452. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14453. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14454. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14455. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14460. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14461. _this._releaseTexture(source_1);
  14462. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14463. continuationCallback();
  14464. });
  14465. }
  14466. return true;
  14467. }, samplingMode);
  14468. };
  14469. if (!fromData || isBase64) {
  14470. if (buffer instanceof HTMLImageElement) {
  14471. onload(buffer);
  14472. }
  14473. else {
  14474. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14475. }
  14476. }
  14477. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14478. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14479. }
  14480. else {
  14481. onload(buffer);
  14482. }
  14483. }
  14484. return texture;
  14485. };
  14486. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14487. var _this = this;
  14488. var rtt = this.createRenderTargetTexture({
  14489. width: destination.width,
  14490. height: destination.height,
  14491. }, {
  14492. generateMipMaps: false,
  14493. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14494. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14495. generateDepthBuffer: false,
  14496. generateStencilBuffer: false
  14497. });
  14498. if (!this._rescalePostProcess) {
  14499. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14500. }
  14501. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14502. _this._rescalePostProcess.onApply = function (effect) {
  14503. effect._bindTexture("textureSampler", source);
  14504. };
  14505. var hostingScene = scene;
  14506. if (!hostingScene) {
  14507. hostingScene = _this.scenes[_this.scenes.length - 1];
  14508. }
  14509. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14510. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14511. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14512. _this.unBindFramebuffer(rtt);
  14513. _this._releaseTexture(rtt);
  14514. if (onComplete) {
  14515. onComplete();
  14516. }
  14517. });
  14518. };
  14519. /**
  14520. * Update a raw texture
  14521. * @param texture defines the texture to update
  14522. * @param data defines the data to store in the texture
  14523. * @param format defines the format of the data
  14524. * @param invertY defines if data must be stored with Y axis inverted
  14525. * @param compression defines the compression used (null by default)
  14526. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14527. */
  14528. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14529. if (compression === void 0) { compression = null; }
  14530. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14531. if (!texture) {
  14532. return;
  14533. }
  14534. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14535. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14536. // babylon's internalFormat but gl's texImage2D format
  14537. var internalFormat = this._getInternalFormat(format);
  14538. var textureType = this._getWebGLTextureType(type);
  14539. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14540. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14541. if (!this._doNotHandleContextLost) {
  14542. texture._bufferView = data;
  14543. texture.format = format;
  14544. texture.type = type;
  14545. texture.invertY = invertY;
  14546. texture._compression = compression;
  14547. }
  14548. if (texture.width % 4 !== 0) {
  14549. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14550. }
  14551. if (compression && data) {
  14552. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14553. }
  14554. else {
  14555. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14556. }
  14557. if (texture.generateMipMaps) {
  14558. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14559. }
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14561. // this.resetTextureCache();
  14562. texture.isReady = true;
  14563. };
  14564. /**
  14565. * Creates a raw texture
  14566. * @param data defines the data to store in the texture
  14567. * @param width defines the width of the texture
  14568. * @param height defines the height of the texture
  14569. * @param format defines the format of the data
  14570. * @param generateMipMaps defines if the engine should generate the mip levels
  14571. * @param invertY defines if data must be stored with Y axis inverted
  14572. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14573. * @param compression defines the compression used (null by default)
  14574. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14575. * @returns the raw texture inside an InternalTexture
  14576. */
  14577. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14578. if (compression === void 0) { compression = null; }
  14579. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14580. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14581. texture.baseWidth = width;
  14582. texture.baseHeight = height;
  14583. texture.width = width;
  14584. texture.height = height;
  14585. texture.format = format;
  14586. texture.generateMipMaps = generateMipMaps;
  14587. texture.samplingMode = samplingMode;
  14588. texture.invertY = invertY;
  14589. texture._compression = compression;
  14590. texture.type = type;
  14591. if (!this._doNotHandleContextLost) {
  14592. texture._bufferView = data;
  14593. }
  14594. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14595. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14596. // Filters
  14597. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14600. if (generateMipMaps) {
  14601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14602. }
  14603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14604. this._internalTexturesCache.push(texture);
  14605. return texture;
  14606. };
  14607. /** @hidden */
  14608. Engine.prototype._unpackFlipY = function (value) {
  14609. if (this._unpackFlipYCached !== value) {
  14610. this._unpackFlipYCached = value;
  14611. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14612. }
  14613. };
  14614. /** @hidden */
  14615. Engine.prototype._getUnpackAlignement = function () {
  14616. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14617. };
  14618. /**
  14619. * Creates a dynamic texture
  14620. * @param width defines the width of the texture
  14621. * @param height defines the height of the texture
  14622. * @param generateMipMaps defines if the engine should generate the mip levels
  14623. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14624. * @returns the dynamic texture inside an InternalTexture
  14625. */
  14626. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14627. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14628. texture.baseWidth = width;
  14629. texture.baseHeight = height;
  14630. if (generateMipMaps) {
  14631. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14632. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14633. }
  14634. // this.resetTextureCache();
  14635. texture.width = width;
  14636. texture.height = height;
  14637. texture.isReady = false;
  14638. texture.generateMipMaps = generateMipMaps;
  14639. texture.samplingMode = samplingMode;
  14640. this.updateTextureSamplingMode(samplingMode, texture);
  14641. this._internalTexturesCache.push(texture);
  14642. return texture;
  14643. };
  14644. /**
  14645. * Update the sampling mode of a given texture
  14646. * @param samplingMode defines the required sampling mode
  14647. * @param texture defines the texture to update
  14648. */
  14649. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14650. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14651. if (texture.isCube) {
  14652. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14653. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14654. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14655. }
  14656. else if (texture.is3D) {
  14657. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14658. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14659. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14660. }
  14661. else {
  14662. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14663. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14665. }
  14666. texture.samplingMode = samplingMode;
  14667. };
  14668. /**
  14669. * Update the content of a dynamic texture
  14670. * @param texture defines the texture to update
  14671. * @param canvas defines the canvas containing the source
  14672. * @param invertY defines if data must be stored with Y axis inverted
  14673. * @param premulAlpha defines if alpha is stored as premultiplied
  14674. * @param format defines the format of the data
  14675. */
  14676. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14677. if (premulAlpha === void 0) { premulAlpha = false; }
  14678. if (!texture) {
  14679. return;
  14680. }
  14681. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14682. this._unpackFlipY(invertY);
  14683. if (premulAlpha) {
  14684. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14685. }
  14686. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14687. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14688. if (texture.generateMipMaps) {
  14689. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14692. if (premulAlpha) {
  14693. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14694. }
  14695. texture.isReady = true;
  14696. };
  14697. /**
  14698. * Update a video texture
  14699. * @param texture defines the texture to update
  14700. * @param video defines the video element to use
  14701. * @param invertY defines if data must be stored with Y axis inverted
  14702. */
  14703. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14704. if (!texture || texture._isDisabled) {
  14705. return;
  14706. }
  14707. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14708. this._unpackFlipY(!invertY); // Video are upside down by default
  14709. try {
  14710. // Testing video texture support
  14711. if (this._videoTextureSupported === undefined) {
  14712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14713. if (this._gl.getError() !== 0) {
  14714. this._videoTextureSupported = false;
  14715. }
  14716. else {
  14717. this._videoTextureSupported = true;
  14718. }
  14719. }
  14720. // Copy video through the current working canvas if video texture is not supported
  14721. if (!this._videoTextureSupported) {
  14722. if (!texture._workingCanvas) {
  14723. texture._workingCanvas = document.createElement("canvas");
  14724. var context = texture._workingCanvas.getContext("2d");
  14725. if (!context) {
  14726. throw new Error("Unable to get 2d context");
  14727. }
  14728. texture._workingContext = context;
  14729. texture._workingCanvas.width = texture.width;
  14730. texture._workingCanvas.height = texture.height;
  14731. }
  14732. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14733. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14734. }
  14735. else {
  14736. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14737. }
  14738. if (texture.generateMipMaps) {
  14739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14740. }
  14741. if (!wasPreviouslyBound) {
  14742. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14743. }
  14744. // this.resetTextureCache();
  14745. texture.isReady = true;
  14746. }
  14747. catch (ex) {
  14748. // Something unexpected
  14749. // Let's disable the texture
  14750. texture._isDisabled = true;
  14751. }
  14752. };
  14753. /**
  14754. * Updates a depth texture Comparison Mode and Function.
  14755. * If the comparison Function is equal to 0, the mode will be set to none.
  14756. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14757. * @param texture The texture to set the comparison function for
  14758. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14759. */
  14760. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14761. if (this.webGLVersion === 1) {
  14762. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14763. return;
  14764. }
  14765. var gl = this._gl;
  14766. if (texture.isCube) {
  14767. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14768. if (comparisonFunction === 0) {
  14769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14771. }
  14772. else {
  14773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14775. }
  14776. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14777. }
  14778. else {
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. if (comparisonFunction === 0) {
  14781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14783. }
  14784. else {
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14787. }
  14788. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14789. }
  14790. texture._comparisonFunction = comparisonFunction;
  14791. };
  14792. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14793. var width = size.width || size;
  14794. var height = size.height || size;
  14795. internalTexture.baseWidth = width;
  14796. internalTexture.baseHeight = height;
  14797. internalTexture.width = width;
  14798. internalTexture.height = height;
  14799. internalTexture.isReady = true;
  14800. internalTexture.samples = 1;
  14801. internalTexture.generateMipMaps = false;
  14802. internalTexture._generateDepthBuffer = true;
  14803. internalTexture._generateStencilBuffer = generateStencil;
  14804. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14805. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14806. internalTexture._comparisonFunction = comparisonFunction;
  14807. var gl = this._gl;
  14808. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14809. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14810. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14811. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14812. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14813. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14814. if (comparisonFunction === 0) {
  14815. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14816. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14817. }
  14818. else {
  14819. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14820. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14821. }
  14822. };
  14823. /**
  14824. * Creates a depth stencil texture.
  14825. * This is only available in WebGL 2 or with the depth texture extension available.
  14826. * @param size The size of face edge in the texture.
  14827. * @param options The options defining the texture.
  14828. * @returns The texture
  14829. */
  14830. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14831. if (options.isCube) {
  14832. var width = size.width || size;
  14833. return this._createDepthStencilCubeTexture(width, options);
  14834. }
  14835. else {
  14836. return this._createDepthStencilTexture(size, options);
  14837. }
  14838. };
  14839. /**
  14840. * Creates a depth stencil texture.
  14841. * This is only available in WebGL 2 or with the depth texture extension available.
  14842. * @param size The size of face edge in the texture.
  14843. * @param options The options defining the texture.
  14844. * @returns The texture
  14845. */
  14846. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14847. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14848. if (!this._caps.depthTextureExtension) {
  14849. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14850. return internalTexture;
  14851. }
  14852. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14853. var gl = this._gl;
  14854. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14855. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14856. if (this.webGLVersion > 1) {
  14857. if (internalOptions.generateStencil) {
  14858. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14859. }
  14860. else {
  14861. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14862. }
  14863. }
  14864. else {
  14865. if (internalOptions.generateStencil) {
  14866. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14867. }
  14868. else {
  14869. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14870. }
  14871. }
  14872. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14873. return internalTexture;
  14874. };
  14875. /**
  14876. * Creates a depth stencil cube texture.
  14877. * This is only available in WebGL 2.
  14878. * @param size The size of face edge in the cube texture.
  14879. * @param options The options defining the cube texture.
  14880. * @returns The cube texture
  14881. */
  14882. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14883. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14884. internalTexture.isCube = true;
  14885. if (this.webGLVersion === 1) {
  14886. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14887. return internalTexture;
  14888. }
  14889. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14890. var gl = this._gl;
  14891. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14892. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14893. // Create the depth/stencil buffer
  14894. for (var face = 0; face < 6; face++) {
  14895. if (internalOptions.generateStencil) {
  14896. 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);
  14897. }
  14898. else {
  14899. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14900. }
  14901. }
  14902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14903. return internalTexture;
  14904. };
  14905. /**
  14906. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14907. * @param renderTarget The render target to set the frame buffer for
  14908. */
  14909. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14910. // Create the framebuffer
  14911. var internalTexture = renderTarget.getInternalTexture();
  14912. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14913. return;
  14914. }
  14915. var gl = this._gl;
  14916. var depthStencilTexture = renderTarget.depthStencilTexture;
  14917. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14918. if (depthStencilTexture.isCube) {
  14919. if (depthStencilTexture._generateStencilBuffer) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14924. }
  14925. }
  14926. else {
  14927. if (depthStencilTexture._generateStencilBuffer) {
  14928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14929. }
  14930. else {
  14931. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14932. }
  14933. }
  14934. this.bindUnboundFramebuffer(null);
  14935. };
  14936. /**
  14937. * Creates a new render target texture
  14938. * @param size defines the size of the texture
  14939. * @param options defines the options used to create the texture
  14940. * @returns a new render target texture stored in an InternalTexture
  14941. */
  14942. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14943. var fullOptions = new RenderTargetCreationOptions();
  14944. if (options !== undefined && typeof options === "object") {
  14945. fullOptions.generateMipMaps = options.generateMipMaps;
  14946. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14947. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14948. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14949. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14950. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14951. }
  14952. else {
  14953. fullOptions.generateMipMaps = options;
  14954. fullOptions.generateDepthBuffer = true;
  14955. fullOptions.generateStencilBuffer = false;
  14956. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14957. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14958. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14959. }
  14960. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14962. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14963. }
  14964. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14966. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14967. }
  14968. var gl = this._gl;
  14969. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14970. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14971. var width = size.width || size;
  14972. var height = size.height || size;
  14973. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14974. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14975. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14976. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14977. }
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14982. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14983. // Create the framebuffer
  14984. var currentFrameBuffer = this._currentFramebuffer;
  14985. var framebuffer = gl.createFramebuffer();
  14986. this.bindUnboundFramebuffer(framebuffer);
  14987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14988. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14989. if (fullOptions.generateMipMaps) {
  14990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14991. }
  14992. // Unbind
  14993. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14994. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14995. this.bindUnboundFramebuffer(currentFrameBuffer);
  14996. texture._framebuffer = framebuffer;
  14997. texture.baseWidth = width;
  14998. texture.baseHeight = height;
  14999. texture.width = width;
  15000. texture.height = height;
  15001. texture.isReady = true;
  15002. texture.samples = 1;
  15003. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15004. texture.samplingMode = fullOptions.samplingMode;
  15005. texture.type = fullOptions.type;
  15006. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15007. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15008. // this.resetTextureCache();
  15009. this._internalTexturesCache.push(texture);
  15010. return texture;
  15011. };
  15012. /**
  15013. * Create a multi render target texture
  15014. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15015. * @param size defines the size of the texture
  15016. * @param options defines the creation options
  15017. * @returns the cube texture as an InternalTexture
  15018. */
  15019. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15020. var generateMipMaps = false;
  15021. var generateDepthBuffer = true;
  15022. var generateStencilBuffer = false;
  15023. var generateDepthTexture = false;
  15024. var textureCount = 1;
  15025. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15027. var types = new Array();
  15028. var samplingModes = new Array();
  15029. if (options !== undefined) {
  15030. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15031. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15032. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15033. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15034. textureCount = options.textureCount || 1;
  15035. if (options.types) {
  15036. types = options.types;
  15037. }
  15038. if (options.samplingModes) {
  15039. samplingModes = options.samplingModes;
  15040. }
  15041. }
  15042. var gl = this._gl;
  15043. // Create the framebuffer
  15044. var framebuffer = gl.createFramebuffer();
  15045. this.bindUnboundFramebuffer(framebuffer);
  15046. var width = size.width || size;
  15047. var height = size.height || size;
  15048. var textures = [];
  15049. var attachments = [];
  15050. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15051. for (var i = 0; i < textureCount; i++) {
  15052. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15053. var type = types[i] || defaultType;
  15054. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15055. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15056. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15057. }
  15058. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15059. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15063. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15064. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15065. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15066. }
  15067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15068. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15069. textures.push(texture);
  15070. attachments.push(attachment);
  15071. gl.activeTexture(gl["TEXTURE" + i]);
  15072. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15073. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15077. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15078. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15079. if (generateMipMaps) {
  15080. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15081. }
  15082. // Unbind
  15083. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15084. texture._framebuffer = framebuffer;
  15085. texture._depthStencilBuffer = depthStencilBuffer;
  15086. texture.baseWidth = width;
  15087. texture.baseHeight = height;
  15088. texture.width = width;
  15089. texture.height = height;
  15090. texture.isReady = true;
  15091. texture.samples = 1;
  15092. texture.generateMipMaps = generateMipMaps;
  15093. texture.samplingMode = samplingMode;
  15094. texture.type = type;
  15095. texture._generateDepthBuffer = generateDepthBuffer;
  15096. texture._generateStencilBuffer = generateStencilBuffer;
  15097. texture._attachments = attachments;
  15098. this._internalTexturesCache.push(texture);
  15099. }
  15100. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15101. // Depth texture
  15102. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15103. gl.activeTexture(gl.TEXTURE0);
  15104. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15109. 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);
  15110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15111. depthTexture._framebuffer = framebuffer;
  15112. depthTexture.baseWidth = width;
  15113. depthTexture.baseHeight = height;
  15114. depthTexture.width = width;
  15115. depthTexture.height = height;
  15116. depthTexture.isReady = true;
  15117. depthTexture.samples = 1;
  15118. depthTexture.generateMipMaps = generateMipMaps;
  15119. depthTexture.samplingMode = gl.NEAREST;
  15120. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15121. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15122. textures.push(depthTexture);
  15123. this._internalTexturesCache.push(depthTexture);
  15124. }
  15125. gl.drawBuffers(attachments);
  15126. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15127. this.bindUnboundFramebuffer(null);
  15128. this.resetTextureCache();
  15129. return textures;
  15130. };
  15131. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15132. if (samples === void 0) { samples = 1; }
  15133. var depthStencilBuffer = null;
  15134. var gl = this._gl;
  15135. // Create the depth/stencil buffer
  15136. if (generateStencilBuffer) {
  15137. depthStencilBuffer = gl.createRenderbuffer();
  15138. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15139. if (samples > 1) {
  15140. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15141. }
  15142. else {
  15143. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15144. }
  15145. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15146. }
  15147. else if (generateDepthBuffer) {
  15148. depthStencilBuffer = gl.createRenderbuffer();
  15149. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15150. if (samples > 1) {
  15151. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15152. }
  15153. else {
  15154. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15155. }
  15156. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15157. }
  15158. return depthStencilBuffer;
  15159. };
  15160. /**
  15161. * Updates the sample count of a render target texture
  15162. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15163. * @param texture defines the texture to update
  15164. * @param samples defines the sample count to set
  15165. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15166. */
  15167. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15168. if (this.webGLVersion < 2 || !texture) {
  15169. return 1;
  15170. }
  15171. if (texture.samples === samples) {
  15172. return samples;
  15173. }
  15174. var gl = this._gl;
  15175. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15176. // Dispose previous render buffers
  15177. if (texture._depthStencilBuffer) {
  15178. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15179. texture._depthStencilBuffer = null;
  15180. }
  15181. if (texture._MSAAFramebuffer) {
  15182. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15183. texture._MSAAFramebuffer = null;
  15184. }
  15185. if (texture._MSAARenderBuffer) {
  15186. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15187. texture._MSAARenderBuffer = null;
  15188. }
  15189. if (samples > 1) {
  15190. var framebuffer = gl.createFramebuffer();
  15191. if (!framebuffer) {
  15192. throw new Error("Unable to create multi sampled framebuffer");
  15193. }
  15194. texture._MSAAFramebuffer = framebuffer;
  15195. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15196. var colorRenderbuffer = gl.createRenderbuffer();
  15197. if (!colorRenderbuffer) {
  15198. throw new Error("Unable to create multi sampled framebuffer");
  15199. }
  15200. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15202. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15203. texture._MSAARenderBuffer = colorRenderbuffer;
  15204. }
  15205. else {
  15206. this.bindUnboundFramebuffer(texture._framebuffer);
  15207. }
  15208. texture.samples = samples;
  15209. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15210. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15211. this.bindUnboundFramebuffer(null);
  15212. return samples;
  15213. };
  15214. /**
  15215. * Update the sample count for a given multiple render target texture
  15216. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15217. * @param textures defines the textures to update
  15218. * @param samples defines the sample count to set
  15219. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15220. */
  15221. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15222. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15223. return 1;
  15224. }
  15225. if (textures[0].samples === samples) {
  15226. return samples;
  15227. }
  15228. var gl = this._gl;
  15229. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15230. // Dispose previous render buffers
  15231. if (textures[0]._depthStencilBuffer) {
  15232. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15233. textures[0]._depthStencilBuffer = null;
  15234. }
  15235. if (textures[0]._MSAAFramebuffer) {
  15236. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15237. textures[0]._MSAAFramebuffer = null;
  15238. }
  15239. for (var i = 0; i < textures.length; i++) {
  15240. if (textures[i]._MSAARenderBuffer) {
  15241. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15242. textures[i]._MSAARenderBuffer = null;
  15243. }
  15244. }
  15245. if (samples > 1) {
  15246. var framebuffer = gl.createFramebuffer();
  15247. if (!framebuffer) {
  15248. throw new Error("Unable to create multi sampled framebuffer");
  15249. }
  15250. this.bindUnboundFramebuffer(framebuffer);
  15251. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15252. var attachments = [];
  15253. for (var i = 0; i < textures.length; i++) {
  15254. var texture = textures[i];
  15255. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15256. var colorRenderbuffer = gl.createRenderbuffer();
  15257. if (!colorRenderbuffer) {
  15258. throw new Error("Unable to create multi sampled framebuffer");
  15259. }
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15261. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15262. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15263. texture._MSAAFramebuffer = framebuffer;
  15264. texture._MSAARenderBuffer = colorRenderbuffer;
  15265. texture.samples = samples;
  15266. texture._depthStencilBuffer = depthStencilBuffer;
  15267. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15268. attachments.push(attachment);
  15269. }
  15270. gl.drawBuffers(attachments);
  15271. }
  15272. else {
  15273. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15274. }
  15275. this.bindUnboundFramebuffer(null);
  15276. return samples;
  15277. };
  15278. /** @hidden */
  15279. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15280. if (faceIndex === void 0) { faceIndex = 0; }
  15281. if (lod === void 0) { lod = 0; }
  15282. var gl = this._gl;
  15283. var target = gl.TEXTURE_2D;
  15284. if (texture.isCube) {
  15285. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15286. }
  15287. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15288. };
  15289. /** @hidden */
  15290. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15291. if (faceIndex === void 0) { faceIndex = 0; }
  15292. if (lod === void 0) { lod = 0; }
  15293. var gl = this._gl;
  15294. var textureType = this._getWebGLTextureType(texture.type);
  15295. var format = this._getInternalFormat(texture.format);
  15296. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15297. this._unpackFlipY(texture.invertY);
  15298. var target = gl.TEXTURE_2D;
  15299. if (texture.isCube) {
  15300. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15301. }
  15302. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15303. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15304. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15305. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15306. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15307. };
  15308. /** @hidden */
  15309. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15310. if (faceIndex === void 0) { faceIndex = 0; }
  15311. if (lod === void 0) { lod = 0; }
  15312. var gl = this._gl;
  15313. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15314. this._bindTextureDirectly(bindTarget, texture, true);
  15315. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15316. this._bindTextureDirectly(bindTarget, null, true);
  15317. };
  15318. /** @hidden */
  15319. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15320. if (faceIndex === void 0) { faceIndex = 0; }
  15321. if (lod === void 0) { lod = 0; }
  15322. var gl = this._gl;
  15323. var textureType = this._getWebGLTextureType(texture.type);
  15324. var format = this._getInternalFormat(texture.format);
  15325. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15326. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15327. this._bindTextureDirectly(bindTarget, texture, true);
  15328. this._unpackFlipY(texture.invertY);
  15329. var target = gl.TEXTURE_2D;
  15330. if (texture.isCube) {
  15331. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15332. }
  15333. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15334. this._bindTextureDirectly(bindTarget, null, true);
  15335. };
  15336. /**
  15337. * Creates a new render target cube texture
  15338. * @param size defines the size of the texture
  15339. * @param options defines the options used to create the texture
  15340. * @returns a new render target cube texture stored in an InternalTexture
  15341. */
  15342. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15343. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15344. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15345. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15346. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15347. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15348. }
  15349. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15350. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15351. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15352. }
  15353. var gl = this._gl;
  15354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15356. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15357. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15358. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15359. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15360. }
  15361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15365. for (var face = 0; face < 6; face++) {
  15366. 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);
  15367. }
  15368. // Create the framebuffer
  15369. var framebuffer = gl.createFramebuffer();
  15370. this.bindUnboundFramebuffer(framebuffer);
  15371. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15372. // MipMaps
  15373. if (fullOptions.generateMipMaps) {
  15374. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15375. }
  15376. // Unbind
  15377. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15379. this.bindUnboundFramebuffer(null);
  15380. texture._framebuffer = framebuffer;
  15381. texture.width = size;
  15382. texture.height = size;
  15383. texture.isReady = true;
  15384. texture.isCube = true;
  15385. texture.samples = 1;
  15386. texture.generateMipMaps = fullOptions.generateMipMaps;
  15387. texture.samplingMode = fullOptions.samplingMode;
  15388. texture.type = fullOptions.type;
  15389. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15390. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15391. this._internalTexturesCache.push(texture);
  15392. return texture;
  15393. };
  15394. /**
  15395. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15396. * @param rootUrl defines the url where the file to load is located
  15397. * @param scene defines the current scene
  15398. * @param lodScale defines scale to apply to the mip map selection
  15399. * @param lodOffset defines offset to apply to the mip map selection
  15400. * @param onLoad defines an optional callback raised when the texture is loaded
  15401. * @param onError defines an optional callback raised if there is an issue to load the texture
  15402. * @param format defines the format of the data
  15403. * @param forcedExtension defines the extension to use to pick the right loader
  15404. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15405. * @returns the cube texture as an InternalTexture
  15406. */
  15407. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15408. var _this = this;
  15409. if (onLoad === void 0) { onLoad = null; }
  15410. if (onError === void 0) { onError = null; }
  15411. if (forcedExtension === void 0) { forcedExtension = null; }
  15412. if (createPolynomials === void 0) { createPolynomials = true; }
  15413. var callback = function (loadData) {
  15414. if (!loadData) {
  15415. if (onLoad) {
  15416. onLoad(null);
  15417. }
  15418. return;
  15419. }
  15420. var texture = loadData.texture;
  15421. if (!createPolynomials) {
  15422. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15423. }
  15424. else if (loadData.info.sphericalPolynomial) {
  15425. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15426. }
  15427. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15428. if (_this._caps.textureLOD) {
  15429. // Do not add extra process if texture lod is supported.
  15430. if (onLoad) {
  15431. onLoad(texture);
  15432. }
  15433. return;
  15434. }
  15435. var mipSlices = 3;
  15436. var gl = _this._gl;
  15437. var width = loadData.width;
  15438. if (!width) {
  15439. return;
  15440. }
  15441. var textures = [];
  15442. for (var i = 0; i < mipSlices; i++) {
  15443. //compute LOD from even spacing in smoothness (matching shader calculation)
  15444. var smoothness = i / (mipSlices - 1);
  15445. var roughness = 1 - smoothness;
  15446. var minLODIndex = lodOffset; // roughness = 0
  15447. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15448. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15449. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15450. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15451. glTextureFromLod.isCube = true;
  15452. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15457. if (loadData.isDDS) {
  15458. var info = loadData.info;
  15459. var data = loadData.data;
  15460. _this._unpackFlipY(info.isCompressed);
  15461. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15462. }
  15463. else {
  15464. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15465. }
  15466. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15467. // Wrap in a base texture for easy binding.
  15468. var lodTexture = new BABYLON.BaseTexture(scene);
  15469. lodTexture.isCube = true;
  15470. lodTexture._texture = glTextureFromLod;
  15471. glTextureFromLod.isReady = true;
  15472. textures.push(lodTexture);
  15473. }
  15474. texture._lodTextureHigh = textures[2];
  15475. texture._lodTextureMid = textures[1];
  15476. texture._lodTextureLow = textures[0];
  15477. if (onLoad) {
  15478. onLoad(texture);
  15479. }
  15480. };
  15481. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15482. };
  15483. /**
  15484. * Creates a cube texture
  15485. * @param rootUrl defines the url where the files to load is located
  15486. * @param scene defines the current scene
  15487. * @param files defines the list of files to load (1 per face)
  15488. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15489. * @param onLoad defines an optional callback raised when the texture is loaded
  15490. * @param onError defines an optional callback raised if there is an issue to load the texture
  15491. * @param format defines the format of the data
  15492. * @param forcedExtension defines the extension to use to pick the right loader
  15493. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15494. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15495. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15496. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15497. * @returns the cube texture as an InternalTexture
  15498. */
  15499. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15500. var _this = this;
  15501. if (onLoad === void 0) { onLoad = null; }
  15502. if (onError === void 0) { onError = null; }
  15503. if (forcedExtension === void 0) { forcedExtension = null; }
  15504. if (createPolynomials === void 0) { createPolynomials = false; }
  15505. if (lodScale === void 0) { lodScale = 0; }
  15506. if (lodOffset === void 0) { lodOffset = 0; }
  15507. if (fallback === void 0) { fallback = null; }
  15508. var gl = this._gl;
  15509. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15510. texture.isCube = true;
  15511. texture.url = rootUrl;
  15512. texture.generateMipMaps = !noMipmap;
  15513. texture._lodGenerationScale = lodScale;
  15514. texture._lodGenerationOffset = lodOffset;
  15515. if (!this._doNotHandleContextLost) {
  15516. texture._extension = forcedExtension;
  15517. texture._files = files;
  15518. }
  15519. var isKTX = false;
  15520. var isDDS = false;
  15521. var isEnv = false;
  15522. var lastDot = rootUrl.lastIndexOf('.');
  15523. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15524. if (this._textureFormatInUse && !fallback) {
  15525. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15526. isKTX = true;
  15527. }
  15528. else {
  15529. isDDS = (extension === ".dds");
  15530. isEnv = (extension === ".env");
  15531. }
  15532. var onerror = function (request, exception) {
  15533. if (isKTX) {
  15534. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15535. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15536. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15537. }
  15538. if (onError && request) {
  15539. onError(request.status + " " + request.statusText, exception);
  15540. }
  15541. };
  15542. if (isKTX) {
  15543. this._loadFile(rootUrl, function (data) {
  15544. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15545. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15546. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15547. _this._unpackFlipY(true);
  15548. ktx.uploadLevels(texture, !noMipmap);
  15549. _this.setCubeMapTextureParams(gl, loadMipmap);
  15550. texture.width = ktx.pixelWidth;
  15551. texture.height = ktx.pixelHeight;
  15552. texture.isReady = true;
  15553. }, undefined, undefined, true, onerror);
  15554. }
  15555. else if (isEnv) {
  15556. this._loadFile(rootUrl, function (data) {
  15557. data = data;
  15558. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15559. if (info) {
  15560. texture.width = info.width;
  15561. texture.height = info.width;
  15562. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15563. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15564. texture.isReady = true;
  15565. if (onLoad) {
  15566. onLoad();
  15567. }
  15568. });
  15569. }
  15570. else if (onError) {
  15571. onError("Can not parse the environment file", null);
  15572. }
  15573. }, undefined, undefined, true, onerror);
  15574. }
  15575. else if (isDDS) {
  15576. if (files && files.length === 6) {
  15577. this._cascadeLoadFiles(scene, function (imgs) {
  15578. var info;
  15579. var loadMipmap = false;
  15580. var width = 0;
  15581. for (var index = 0; index < imgs.length; index++) {
  15582. var data = imgs[index];
  15583. info = BABYLON.DDSTools.GetDDSInfo(data);
  15584. texture.width = info.width;
  15585. texture.height = info.height;
  15586. width = info.width;
  15587. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15588. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15589. _this._unpackFlipY(info.isCompressed);
  15590. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15591. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15592. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15593. }
  15594. }
  15595. _this.setCubeMapTextureParams(gl, loadMipmap);
  15596. texture.isReady = true;
  15597. if (onLoad) {
  15598. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15599. }
  15600. }, files, onError);
  15601. }
  15602. else {
  15603. this._loadFile(rootUrl, function (data) {
  15604. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15605. texture.width = info.width;
  15606. texture.height = info.height;
  15607. if (createPolynomials) {
  15608. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15609. }
  15610. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15612. _this._unpackFlipY(info.isCompressed);
  15613. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15614. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15615. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15616. }
  15617. _this.setCubeMapTextureParams(gl, loadMipmap);
  15618. texture.isReady = true;
  15619. if (onLoad) {
  15620. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15621. }
  15622. }, undefined, undefined, true, onerror);
  15623. }
  15624. }
  15625. else {
  15626. if (!files) {
  15627. throw new Error("Cannot load cubemap because files were not defined");
  15628. }
  15629. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15630. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15631. var height = width;
  15632. _this._prepareWorkingCanvas();
  15633. if (!_this._workingCanvas || !_this._workingContext) {
  15634. return;
  15635. }
  15636. _this._workingCanvas.width = width;
  15637. _this._workingCanvas.height = height;
  15638. var faces = [
  15639. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15640. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15641. ];
  15642. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15643. _this._unpackFlipY(false);
  15644. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15645. for (var index = 0; index < faces.length; index++) {
  15646. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15647. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15648. }
  15649. if (!noMipmap) {
  15650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15651. }
  15652. _this.setCubeMapTextureParams(gl, !noMipmap);
  15653. texture.width = width;
  15654. texture.height = height;
  15655. texture.isReady = true;
  15656. if (format) {
  15657. texture.format = format;
  15658. }
  15659. texture.onLoadedObservable.notifyObservers(texture);
  15660. texture.onLoadedObservable.clear();
  15661. if (onLoad) {
  15662. onLoad();
  15663. }
  15664. }, files, onError);
  15665. }
  15666. this._internalTexturesCache.push(texture);
  15667. return texture;
  15668. };
  15669. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15674. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15675. // this.resetTextureCache();
  15676. };
  15677. /**
  15678. * Update a raw cube texture
  15679. * @param texture defines the texture to udpdate
  15680. * @param data defines the data to store
  15681. * @param format defines the data format
  15682. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15683. * @param invertY defines if data must be stored with Y axis inverted
  15684. * @param compression defines the compression used (null by default)
  15685. * @param level defines which level of the texture to update
  15686. */
  15687. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15688. if (compression === void 0) { compression = null; }
  15689. if (level === void 0) { level = 0; }
  15690. texture._bufferViewArray = data;
  15691. texture.format = format;
  15692. texture.type = type;
  15693. texture.invertY = invertY;
  15694. texture._compression = compression;
  15695. var gl = this._gl;
  15696. var textureType = this._getWebGLTextureType(type);
  15697. var internalFormat = this._getInternalFormat(format);
  15698. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15699. var needConversion = false;
  15700. if (internalFormat === gl.RGB) {
  15701. internalFormat = gl.RGBA;
  15702. needConversion = true;
  15703. }
  15704. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15705. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15706. if (texture.width % 4 !== 0) {
  15707. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15708. }
  15709. // Data are known to be in +X +Y +Z -X -Y -Z
  15710. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15711. var faceData = data[faceIndex];
  15712. if (compression) {
  15713. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15714. }
  15715. else {
  15716. if (needConversion) {
  15717. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15718. }
  15719. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15720. }
  15721. }
  15722. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15723. if (isPot && texture.generateMipMaps && level === 0) {
  15724. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15725. }
  15726. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15727. // this.resetTextureCache();
  15728. texture.isReady = true;
  15729. };
  15730. /**
  15731. * Creates a new raw cube texture
  15732. * @param data defines the array of data to use to create each face
  15733. * @param size defines the size of the textures
  15734. * @param format defines the format of the data
  15735. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15736. * @param generateMipMaps defines if the engine should generate the mip levels
  15737. * @param invertY defines if data must be stored with Y axis inverted
  15738. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15739. * @param compression defines the compression used (null by default)
  15740. * @returns the cube texture as an InternalTexture
  15741. */
  15742. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15743. if (compression === void 0) { compression = null; }
  15744. var gl = this._gl;
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15746. texture.isCube = true;
  15747. texture.generateMipMaps = generateMipMaps;
  15748. texture.format = format;
  15749. texture.type = type;
  15750. if (!this._doNotHandleContextLost) {
  15751. texture._bufferViewArray = data;
  15752. }
  15753. var textureType = this._getWebGLTextureType(type);
  15754. var internalFormat = this._getInternalFormat(format);
  15755. if (internalFormat === gl.RGB) {
  15756. internalFormat = gl.RGBA;
  15757. }
  15758. var width = size;
  15759. var height = width;
  15760. texture.width = width;
  15761. texture.height = height;
  15762. // Double check on POT to generate Mips.
  15763. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15764. if (!isPot) {
  15765. generateMipMaps = false;
  15766. }
  15767. // Upload data if needed. The texture won't be ready until then.
  15768. if (data) {
  15769. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15770. }
  15771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15772. // Filters
  15773. if (data && generateMipMaps) {
  15774. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15775. }
  15776. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15779. }
  15780. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15783. }
  15784. else {
  15785. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15788. }
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15791. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15792. return texture;
  15793. };
  15794. /**
  15795. * Creates a new raw cube texture from a specified url
  15796. * @param url defines the url where the data is located
  15797. * @param scene defines the current scene
  15798. * @param size defines the size of the textures
  15799. * @param format defines the format of the data
  15800. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15801. * @param noMipmap defines if the engine should avoid generating the mip levels
  15802. * @param callback defines a callback used to extract texture data from loaded data
  15803. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15804. * @param onLoad defines a callback called when texture is loaded
  15805. * @param onError defines a callback called if there is an error
  15806. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15807. * @param invertY defines if data must be stored with Y axis inverted
  15808. * @returns the cube texture as an InternalTexture
  15809. */
  15810. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15811. var _this = this;
  15812. if (onLoad === void 0) { onLoad = null; }
  15813. if (onError === void 0) { onError = null; }
  15814. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15815. if (invertY === void 0) { invertY = false; }
  15816. var gl = this._gl;
  15817. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15818. scene._addPendingData(texture);
  15819. texture.url = url;
  15820. this._internalTexturesCache.push(texture);
  15821. var onerror = function (request, exception) {
  15822. scene._removePendingData(texture);
  15823. if (onError && request) {
  15824. onError(request.status + " " + request.statusText, exception);
  15825. }
  15826. };
  15827. var internalCallback = function (data) {
  15828. var width = texture.width;
  15829. var faceDataArrays = callback(data);
  15830. if (!faceDataArrays) {
  15831. return;
  15832. }
  15833. if (mipmapGenerator) {
  15834. var textureType = _this._getWebGLTextureType(type);
  15835. var internalFormat = _this._getInternalFormat(format);
  15836. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15837. var needConversion = false;
  15838. if (internalFormat === gl.RGB) {
  15839. internalFormat = gl.RGBA;
  15840. needConversion = true;
  15841. }
  15842. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15843. _this._unpackFlipY(false);
  15844. var mipData = mipmapGenerator(faceDataArrays);
  15845. for (var level = 0; level < mipData.length; level++) {
  15846. var mipSize = width >> level;
  15847. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15848. var mipFaceData = mipData[level][faceIndex];
  15849. if (needConversion) {
  15850. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15851. }
  15852. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15853. }
  15854. }
  15855. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15856. }
  15857. else {
  15858. texture.generateMipMaps = !noMipmap;
  15859. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15860. texture.generateMipMaps = false;
  15861. }
  15862. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15863. }
  15864. texture.isReady = true;
  15865. // this.resetTextureCache();
  15866. scene._removePendingData(texture);
  15867. if (onLoad) {
  15868. onLoad();
  15869. }
  15870. };
  15871. this._loadFile(url, function (data) {
  15872. internalCallback(data);
  15873. }, undefined, scene.database, true, onerror);
  15874. return texture;
  15875. };
  15876. ;
  15877. /**
  15878. * Update a raw 3D texture
  15879. * @param texture defines the texture to update
  15880. * @param data defines the data to store
  15881. * @param format defines the data format
  15882. * @param invertY defines if data must be stored with Y axis inverted
  15883. * @param compression defines the used compression (can be null)
  15884. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15885. */
  15886. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15887. if (compression === void 0) { compression = null; }
  15888. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15889. var internalType = this._getWebGLTextureType(textureType);
  15890. var internalFormat = this._getInternalFormat(format);
  15891. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15892. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15893. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15894. if (!this._doNotHandleContextLost) {
  15895. texture._bufferView = data;
  15896. texture.format = format;
  15897. texture.invertY = invertY;
  15898. texture._compression = compression;
  15899. }
  15900. if (texture.width % 4 !== 0) {
  15901. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15902. }
  15903. if (compression && data) {
  15904. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15905. }
  15906. else {
  15907. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15908. }
  15909. if (texture.generateMipMaps) {
  15910. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15911. }
  15912. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15913. // this.resetTextureCache();
  15914. texture.isReady = true;
  15915. };
  15916. /**
  15917. * Creates a new raw 3D texture
  15918. * @param data defines the data used to create the texture
  15919. * @param width defines the width of the texture
  15920. * @param height defines the height of the texture
  15921. * @param depth defines the depth of the texture
  15922. * @param format defines the format of the texture
  15923. * @param generateMipMaps defines if the engine must generate mip levels
  15924. * @param invertY defines if data must be stored with Y axis inverted
  15925. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15926. * @param compression defines the compressed used (can be null)
  15927. * @param textureType defines the compressed used (can be null)
  15928. * @returns a new raw 3D texture (stored in an InternalTexture)
  15929. */
  15930. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15931. if (compression === void 0) { compression = null; }
  15932. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15933. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15934. texture.baseWidth = width;
  15935. texture.baseHeight = height;
  15936. texture.baseDepth = depth;
  15937. texture.width = width;
  15938. texture.height = height;
  15939. texture.depth = depth;
  15940. texture.format = format;
  15941. texture.type = textureType;
  15942. texture.generateMipMaps = generateMipMaps;
  15943. texture.samplingMode = samplingMode;
  15944. texture.is3D = true;
  15945. if (!this._doNotHandleContextLost) {
  15946. texture._bufferView = data;
  15947. }
  15948. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15949. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15950. // Filters
  15951. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15952. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15953. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15954. if (generateMipMaps) {
  15955. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15956. }
  15957. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15958. this._internalTexturesCache.push(texture);
  15959. return texture;
  15960. };
  15961. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15962. var gl = this._gl;
  15963. if (!gl) {
  15964. return;
  15965. }
  15966. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15969. if (!noMipmap && !isCompressed) {
  15970. gl.generateMipmap(gl.TEXTURE_2D);
  15971. }
  15972. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15973. // this.resetTextureCache();
  15974. if (scene) {
  15975. scene._removePendingData(texture);
  15976. }
  15977. texture.onLoadedObservable.notifyObservers(texture);
  15978. texture.onLoadedObservable.clear();
  15979. };
  15980. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15981. var _this = this;
  15982. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15983. var maxTextureSize = this.getCaps().maxTextureSize;
  15984. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15985. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15986. var gl = this._gl;
  15987. if (!gl) {
  15988. return;
  15989. }
  15990. if (!texture._webGLTexture) {
  15991. // this.resetTextureCache();
  15992. if (scene) {
  15993. scene._removePendingData(texture);
  15994. }
  15995. return;
  15996. }
  15997. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15998. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15999. texture.baseWidth = width;
  16000. texture.baseHeight = height;
  16001. texture.width = potWidth;
  16002. texture.height = potHeight;
  16003. texture.isReady = true;
  16004. if (processFunction(potWidth, potHeight, function () {
  16005. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16006. })) {
  16007. // Returning as texture needs extra async steps
  16008. return;
  16009. }
  16010. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16011. };
  16012. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16013. // Create new RGBA data container.
  16014. var rgbaData;
  16015. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16016. rgbaData = new Float32Array(width * height * 4);
  16017. }
  16018. else {
  16019. rgbaData = new Uint32Array(width * height * 4);
  16020. }
  16021. // Convert each pixel.
  16022. for (var x = 0; x < width; x++) {
  16023. for (var y = 0; y < height; y++) {
  16024. var index = (y * width + x) * 3;
  16025. var newIndex = (y * width + x) * 4;
  16026. // Map Old Value to new value.
  16027. rgbaData[newIndex + 0] = rgbData[index + 0];
  16028. rgbaData[newIndex + 1] = rgbData[index + 1];
  16029. rgbaData[newIndex + 2] = rgbData[index + 2];
  16030. // Add fully opaque alpha channel.
  16031. rgbaData[newIndex + 3] = 1;
  16032. }
  16033. }
  16034. return rgbaData;
  16035. };
  16036. /** @hidden */
  16037. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16038. var gl = this._gl;
  16039. if (texture._framebuffer) {
  16040. gl.deleteFramebuffer(texture._framebuffer);
  16041. texture._framebuffer = null;
  16042. }
  16043. if (texture._depthStencilBuffer) {
  16044. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16045. texture._depthStencilBuffer = null;
  16046. }
  16047. if (texture._MSAAFramebuffer) {
  16048. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16049. texture._MSAAFramebuffer = null;
  16050. }
  16051. if (texture._MSAARenderBuffer) {
  16052. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16053. texture._MSAARenderBuffer = null;
  16054. }
  16055. };
  16056. /** @hidden */
  16057. Engine.prototype._releaseTexture = function (texture) {
  16058. var gl = this._gl;
  16059. this._releaseFramebufferObjects(texture);
  16060. gl.deleteTexture(texture._webGLTexture);
  16061. // Unbind channels
  16062. this.unbindAllTextures();
  16063. var index = this._internalTexturesCache.indexOf(texture);
  16064. if (index !== -1) {
  16065. this._internalTexturesCache.splice(index, 1);
  16066. }
  16067. // Integrated fixed lod samplers.
  16068. if (texture._lodTextureHigh) {
  16069. texture._lodTextureHigh.dispose();
  16070. }
  16071. if (texture._lodTextureMid) {
  16072. texture._lodTextureMid.dispose();
  16073. }
  16074. if (texture._lodTextureLow) {
  16075. texture._lodTextureLow.dispose();
  16076. }
  16077. // Set output texture of post process to null if the texture has been released/disposed
  16078. this.scenes.forEach(function (scene) {
  16079. scene.postProcesses.forEach(function (postProcess) {
  16080. if (postProcess._outputTexture == texture) {
  16081. postProcess._outputTexture = null;
  16082. }
  16083. });
  16084. scene.cameras.forEach(function (camera) {
  16085. camera._postProcesses.forEach(function (postProcess) {
  16086. if (postProcess) {
  16087. if (postProcess._outputTexture == texture) {
  16088. postProcess._outputTexture = null;
  16089. }
  16090. }
  16091. });
  16092. });
  16093. });
  16094. };
  16095. Engine.prototype.setProgram = function (program) {
  16096. if (this._currentProgram !== program) {
  16097. this._gl.useProgram(program);
  16098. this._currentProgram = program;
  16099. }
  16100. };
  16101. /**
  16102. * Binds an effect to the webGL context
  16103. * @param effect defines the effect to bind
  16104. */
  16105. Engine.prototype.bindSamplers = function (effect) {
  16106. this.setProgram(effect.getProgram());
  16107. var samplers = effect.getSamplers();
  16108. for (var index = 0; index < samplers.length; index++) {
  16109. var uniform = effect.getUniform(samplers[index]);
  16110. if (uniform) {
  16111. this._boundUniforms[index] = uniform;
  16112. }
  16113. }
  16114. this._currentEffect = null;
  16115. };
  16116. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16117. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16118. return;
  16119. }
  16120. // Remove
  16121. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16122. // Bind last to it
  16123. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16124. // Bind to dummy
  16125. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16126. };
  16127. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16128. if (!internalTexture) {
  16129. return -1;
  16130. }
  16131. internalTexture._initialSlot = channel;
  16132. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16133. if (channel !== internalTexture._designatedSlot) {
  16134. this._textureCollisions.addCount(1, false);
  16135. }
  16136. }
  16137. else {
  16138. if (channel !== internalTexture._designatedSlot) {
  16139. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16140. return internalTexture._designatedSlot;
  16141. }
  16142. else {
  16143. // No slot for this texture, let's pick a new one (if we find a free slot)
  16144. if (this._nextFreeTextureSlots.length) {
  16145. return this._nextFreeTextureSlots[0];
  16146. }
  16147. // We need to recycle the oldest bound texture, sorry.
  16148. this._textureCollisions.addCount(1, false);
  16149. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16150. }
  16151. }
  16152. }
  16153. return channel;
  16154. };
  16155. Engine.prototype._linkTrackers = function (previous, next) {
  16156. previous.next = next;
  16157. next.previous = previous;
  16158. };
  16159. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16160. var currentSlot = internalTexture._designatedSlot;
  16161. if (currentSlot === -1) {
  16162. return -1;
  16163. }
  16164. internalTexture._designatedSlot = -1;
  16165. if (this.disableTextureBindingOptimization) {
  16166. return -1;
  16167. }
  16168. // Remove from bound list
  16169. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16170. // Free the slot
  16171. this._boundTexturesCache[currentSlot] = null;
  16172. this._nextFreeTextureSlots.push(currentSlot);
  16173. return currentSlot;
  16174. };
  16175. Engine.prototype._activateCurrentTexture = function () {
  16176. if (this._currentTextureChannel !== this._activeChannel) {
  16177. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16178. this._currentTextureChannel = this._activeChannel;
  16179. }
  16180. };
  16181. /** @hidden */
  16182. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16183. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16184. if (force === void 0) { force = false; }
  16185. var wasPreviouslyBound = false;
  16186. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16187. this._activeChannel = texture._designatedSlot;
  16188. }
  16189. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16190. var isTextureForRendering = texture && texture._initialSlot > -1;
  16191. if (currentTextureBound !== texture || force) {
  16192. if (currentTextureBound) {
  16193. this._removeDesignatedSlot(currentTextureBound);
  16194. }
  16195. this._activateCurrentTexture();
  16196. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16197. this._boundTexturesCache[this._activeChannel] = texture;
  16198. if (texture) {
  16199. if (!this.disableTextureBindingOptimization) {
  16200. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16201. if (slotIndex > -1) {
  16202. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16203. }
  16204. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16205. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16206. }
  16207. texture._designatedSlot = this._activeChannel;
  16208. }
  16209. }
  16210. else if (forTextureDataUpdate) {
  16211. wasPreviouslyBound = true;
  16212. this._activateCurrentTexture();
  16213. }
  16214. if (isTextureForRendering && !forTextureDataUpdate) {
  16215. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16216. }
  16217. return wasPreviouslyBound;
  16218. };
  16219. /** @hidden */
  16220. Engine.prototype._bindTexture = function (channel, texture) {
  16221. if (channel < 0) {
  16222. return;
  16223. }
  16224. if (texture) {
  16225. channel = this._getCorrectTextureChannel(channel, texture);
  16226. }
  16227. this._activeChannel = channel;
  16228. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16229. };
  16230. /**
  16231. * Sets a texture to the webGL context from a postprocess
  16232. * @param channel defines the channel to use
  16233. * @param postProcess defines the source postprocess
  16234. */
  16235. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16236. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16237. };
  16238. /**
  16239. * Binds the output of the passed in post process to the texture channel specified
  16240. * @param channel The channel the texture should be bound to
  16241. * @param postProcess The post process which's output should be bound
  16242. */
  16243. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16244. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16245. };
  16246. /**
  16247. * Unbind all textures from the webGL context
  16248. */
  16249. Engine.prototype.unbindAllTextures = function () {
  16250. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16251. this._activeChannel = channel;
  16252. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16253. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16254. if (this.webGLVersion > 1) {
  16255. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16256. }
  16257. }
  16258. };
  16259. /**
  16260. * Sets a texture to the according uniform.
  16261. * @param channel The texture channel
  16262. * @param uniform The uniform to set
  16263. * @param texture The texture to apply
  16264. */
  16265. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16266. if (channel < 0) {
  16267. return;
  16268. }
  16269. if (uniform) {
  16270. this._boundUniforms[channel] = uniform;
  16271. }
  16272. this._setTexture(channel, texture);
  16273. };
  16274. /**
  16275. * Sets a depth stencil texture from a render target to the according uniform.
  16276. * @param channel The texture channel
  16277. * @param uniform The uniform to set
  16278. * @param texture The render target texture containing the depth stencil texture to apply
  16279. */
  16280. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16281. if (channel < 0) {
  16282. return;
  16283. }
  16284. if (uniform) {
  16285. this._boundUniforms[channel] = uniform;
  16286. }
  16287. if (!texture || !texture.depthStencilTexture) {
  16288. this._setTexture(channel, null);
  16289. }
  16290. else {
  16291. this._setTexture(channel, texture, false, true);
  16292. }
  16293. };
  16294. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16295. var uniform = this._boundUniforms[sourceSlot];
  16296. if (uniform._currentState === destination) {
  16297. return;
  16298. }
  16299. this._gl.uniform1i(uniform, destination);
  16300. uniform._currentState = destination;
  16301. };
  16302. Engine.prototype._getTextureWrapMode = function (mode) {
  16303. switch (mode) {
  16304. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16305. return this._gl.REPEAT;
  16306. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16307. return this._gl.CLAMP_TO_EDGE;
  16308. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16309. return this._gl.MIRRORED_REPEAT;
  16310. }
  16311. return this._gl.REPEAT;
  16312. };
  16313. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16314. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16315. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16316. // Not ready?
  16317. if (!texture) {
  16318. if (this._boundTexturesCache[channel] != null) {
  16319. this._activeChannel = channel;
  16320. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16321. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16322. if (this.webGLVersion > 1) {
  16323. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16324. }
  16325. }
  16326. return false;
  16327. }
  16328. // Video
  16329. if (texture.video) {
  16330. this._activeChannel = channel;
  16331. texture.update();
  16332. }
  16333. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16334. texture.delayLoad();
  16335. return false;
  16336. }
  16337. var internalTexture;
  16338. if (depthStencilTexture) {
  16339. internalTexture = texture.depthStencilTexture;
  16340. }
  16341. else if (texture.isReady()) {
  16342. internalTexture = texture.getInternalTexture();
  16343. }
  16344. else if (texture.isCube) {
  16345. internalTexture = this.emptyCubeTexture;
  16346. }
  16347. else if (texture.is3D) {
  16348. internalTexture = this.emptyTexture3D;
  16349. }
  16350. else {
  16351. internalTexture = this.emptyTexture;
  16352. }
  16353. if (!isPartOfTextureArray) {
  16354. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16355. }
  16356. var needToBind = true;
  16357. if (this._boundTexturesCache[channel] === internalTexture) {
  16358. this._moveBoundTextureOnTop(internalTexture);
  16359. if (!isPartOfTextureArray) {
  16360. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16361. }
  16362. needToBind = false;
  16363. }
  16364. this._activeChannel = channel;
  16365. if (internalTexture && internalTexture.is3D) {
  16366. if (needToBind) {
  16367. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16368. }
  16369. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16370. internalTexture._cachedWrapU = texture.wrapU;
  16371. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16372. }
  16373. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16374. internalTexture._cachedWrapV = texture.wrapV;
  16375. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16376. }
  16377. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16378. internalTexture._cachedWrapR = texture.wrapR;
  16379. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16380. }
  16381. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16382. }
  16383. else if (internalTexture && internalTexture.isCube) {
  16384. if (needToBind) {
  16385. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16386. }
  16387. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16388. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16389. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16390. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16392. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16393. }
  16394. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16395. }
  16396. else {
  16397. if (needToBind) {
  16398. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16401. internalTexture._cachedWrapU = texture.wrapU;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16403. }
  16404. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16405. internalTexture._cachedWrapV = texture.wrapV;
  16406. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16407. }
  16408. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16409. }
  16410. return true;
  16411. };
  16412. /**
  16413. * Sets an array of texture to the webGL context
  16414. * @param channel defines the channel where the texture array must be set
  16415. * @param uniform defines the associated uniform location
  16416. * @param textures defines the array of textures to bind
  16417. */
  16418. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16419. if (channel < 0 || !uniform) {
  16420. return;
  16421. }
  16422. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16423. this._textureUnits = new Int32Array(textures.length);
  16424. }
  16425. for (var i = 0; i < textures.length; i++) {
  16426. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16427. }
  16428. this._gl.uniform1iv(uniform, this._textureUnits);
  16429. for (var index = 0; index < textures.length; index++) {
  16430. this._setTexture(this._textureUnits[index], textures[index], true);
  16431. }
  16432. };
  16433. /** @hidden */
  16434. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16435. var internalTexture = texture.getInternalTexture();
  16436. if (!internalTexture) {
  16437. return;
  16438. }
  16439. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16440. var value = texture.anisotropicFilteringLevel;
  16441. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16442. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16443. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16444. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16445. }
  16446. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16447. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16448. internalTexture._cachedAnisotropicFilteringLevel = value;
  16449. }
  16450. };
  16451. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16452. this._bindTextureDirectly(target, texture, true, true);
  16453. this._gl.texParameterf(target, parameter, value);
  16454. };
  16455. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16456. if (texture) {
  16457. this._bindTextureDirectly(target, texture, true, true);
  16458. }
  16459. this._gl.texParameteri(target, parameter, value);
  16460. };
  16461. /**
  16462. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16463. * @param x defines the x coordinate of the rectangle where pixels must be read
  16464. * @param y defines the y coordinate of the rectangle where pixels must be read
  16465. * @param width defines the width of the rectangle where pixels must be read
  16466. * @param height defines the height of the rectangle where pixels must be read
  16467. * @returns a Uint8Array containing RGBA colors
  16468. */
  16469. Engine.prototype.readPixels = function (x, y, width, height) {
  16470. var data = new Uint8Array(height * width * 4);
  16471. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16472. return data;
  16473. };
  16474. /**
  16475. * Add an externaly attached data from its key.
  16476. * This method call will fail and return false, if such key already exists.
  16477. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16478. * @param key the unique key that identifies the data
  16479. * @param data the data object to associate to the key for this Engine instance
  16480. * @return true if no such key were already present and the data was added successfully, false otherwise
  16481. */
  16482. Engine.prototype.addExternalData = function (key, data) {
  16483. if (!this._externalData) {
  16484. this._externalData = new BABYLON.StringDictionary();
  16485. }
  16486. return this._externalData.add(key, data);
  16487. };
  16488. /**
  16489. * Get an externaly attached data from its key
  16490. * @param key the unique key that identifies the data
  16491. * @return the associated data, if present (can be null), or undefined if not present
  16492. */
  16493. Engine.prototype.getExternalData = function (key) {
  16494. if (!this._externalData) {
  16495. this._externalData = new BABYLON.StringDictionary();
  16496. }
  16497. return this._externalData.get(key);
  16498. };
  16499. /**
  16500. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16501. * @param key the unique key that identifies the data
  16502. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16503. * @return the associated data, can be null if the factory returned null.
  16504. */
  16505. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.getOrAddWithFactory(key, factory);
  16510. };
  16511. /**
  16512. * Remove an externaly attached data from the Engine instance
  16513. * @param key the unique key that identifies the data
  16514. * @return true if the data was successfully removed, false if it doesn't exist
  16515. */
  16516. Engine.prototype.removeExternalData = function (key) {
  16517. if (!this._externalData) {
  16518. this._externalData = new BABYLON.StringDictionary();
  16519. }
  16520. return this._externalData.remove(key);
  16521. };
  16522. /**
  16523. * Unbind all vertex attributes from the webGL context
  16524. */
  16525. Engine.prototype.unbindAllAttributes = function () {
  16526. if (this._mustWipeVertexAttributes) {
  16527. this._mustWipeVertexAttributes = false;
  16528. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16529. this._gl.disableVertexAttribArray(i);
  16530. this._vertexAttribArraysEnabled[i] = false;
  16531. this._currentBufferPointers[i].active = false;
  16532. }
  16533. return;
  16534. }
  16535. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16536. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16537. continue;
  16538. }
  16539. this._gl.disableVertexAttribArray(i);
  16540. this._vertexAttribArraysEnabled[i] = false;
  16541. this._currentBufferPointers[i].active = false;
  16542. }
  16543. };
  16544. /**
  16545. * 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
  16546. */
  16547. Engine.prototype.releaseEffects = function () {
  16548. for (var name in this._compiledEffects) {
  16549. this._deleteProgram(this._compiledEffects[name]._program);
  16550. }
  16551. this._compiledEffects = {};
  16552. };
  16553. /**
  16554. * Dispose and release all associated resources
  16555. */
  16556. Engine.prototype.dispose = function () {
  16557. this.hideLoadingUI();
  16558. this.stopRenderLoop();
  16559. // Release postProcesses
  16560. while (this.postProcesses.length) {
  16561. this.postProcesses[0].dispose();
  16562. }
  16563. // Empty texture
  16564. if (this._emptyTexture) {
  16565. this._releaseTexture(this._emptyTexture);
  16566. this._emptyTexture = null;
  16567. }
  16568. if (this._emptyCubeTexture) {
  16569. this._releaseTexture(this._emptyCubeTexture);
  16570. this._emptyCubeTexture = null;
  16571. }
  16572. // Rescale PP
  16573. if (this._rescalePostProcess) {
  16574. this._rescalePostProcess.dispose();
  16575. }
  16576. // Release scenes
  16577. while (this.scenes.length) {
  16578. this.scenes[0].dispose();
  16579. }
  16580. // Release audio engine
  16581. if (Engine.audioEngine) {
  16582. Engine.audioEngine.dispose();
  16583. }
  16584. // Release effects
  16585. this.releaseEffects();
  16586. // Unbind
  16587. this.unbindAllAttributes();
  16588. this._boundUniforms = [];
  16589. if (this._dummyFramebuffer) {
  16590. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16591. }
  16592. //WebVR
  16593. this.disableVR();
  16594. // Events
  16595. if (BABYLON.Tools.IsWindowObjectExist()) {
  16596. window.removeEventListener("blur", this._onBlur);
  16597. window.removeEventListener("focus", this._onFocus);
  16598. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16599. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16600. if (this._renderingCanvas) {
  16601. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16602. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16603. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16604. if (!this._doNotHandleContextLost) {
  16605. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16606. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16607. }
  16608. }
  16609. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16610. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16611. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16612. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16613. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16614. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16615. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16616. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16617. if (this._onVrDisplayConnect) {
  16618. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16619. if (this._onVrDisplayDisconnect) {
  16620. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16621. }
  16622. if (this._onVrDisplayPresentChange) {
  16623. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16624. }
  16625. this._onVrDisplayConnect = null;
  16626. this._onVrDisplayDisconnect = null;
  16627. }
  16628. }
  16629. // Remove from Instances
  16630. var index = Engine.Instances.indexOf(this);
  16631. if (index >= 0) {
  16632. Engine.Instances.splice(index, 1);
  16633. }
  16634. this._workingCanvas = null;
  16635. this._workingContext = null;
  16636. this._currentBufferPointers = [];
  16637. this._renderingCanvas = null;
  16638. this._currentProgram = null;
  16639. this._bindedRenderFunction = null;
  16640. this.onResizeObservable.clear();
  16641. this.onCanvasBlurObservable.clear();
  16642. this.onCanvasFocusObservable.clear();
  16643. this.onCanvasPointerOutObservable.clear();
  16644. this.onBeginFrameObservable.clear();
  16645. this.onEndFrameObservable.clear();
  16646. BABYLON.Effect.ResetCache();
  16647. // Abort active requests
  16648. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16649. var request = _a[_i];
  16650. request.abort();
  16651. }
  16652. };
  16653. // Loading screen
  16654. /**
  16655. * Display the loading screen
  16656. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16657. */
  16658. Engine.prototype.displayLoadingUI = function () {
  16659. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16660. return;
  16661. }
  16662. var loadingScreen = this.loadingScreen;
  16663. if (loadingScreen) {
  16664. loadingScreen.displayLoadingUI();
  16665. }
  16666. };
  16667. /**
  16668. * Hide the loading screen
  16669. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16670. */
  16671. Engine.prototype.hideLoadingUI = function () {
  16672. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16673. return;
  16674. }
  16675. var loadingScreen = this.loadingScreen;
  16676. if (loadingScreen) {
  16677. loadingScreen.hideLoadingUI();
  16678. }
  16679. };
  16680. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16681. /**
  16682. * Gets the current loading screen object
  16683. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16684. */
  16685. get: function () {
  16686. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16687. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16688. return this._loadingScreen;
  16689. },
  16690. /**
  16691. * Sets the current loading screen object
  16692. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16693. */
  16694. set: function (loadingScreen) {
  16695. this._loadingScreen = loadingScreen;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16701. /**
  16702. * Sets the current loading screen text
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. set: function (text) {
  16706. this.loadingScreen.loadingUIText = text;
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16712. /**
  16713. * Sets the current loading screen background color
  16714. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16715. */
  16716. set: function (color) {
  16717. this.loadingScreen.loadingUIBackgroundColor = color;
  16718. },
  16719. enumerable: true,
  16720. configurable: true
  16721. });
  16722. /**
  16723. * Attach a new callback raised when context lost event is fired
  16724. * @param callback defines the callback to call
  16725. */
  16726. Engine.prototype.attachContextLostEvent = function (callback) {
  16727. if (this._renderingCanvas) {
  16728. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16729. }
  16730. };
  16731. /**
  16732. * Attach a new callback raised when context restored event is fired
  16733. * @param callback defines the callback to call
  16734. */
  16735. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16736. if (this._renderingCanvas) {
  16737. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16738. }
  16739. };
  16740. /**
  16741. * Gets the source code of the vertex shader associated with a specific webGL program
  16742. * @param program defines the program to use
  16743. * @returns a string containing the source code of the vertex shader associated with the program
  16744. */
  16745. Engine.prototype.getVertexShaderSource = function (program) {
  16746. var shaders = this._gl.getAttachedShaders(program);
  16747. if (!shaders) {
  16748. return null;
  16749. }
  16750. return this._gl.getShaderSource(shaders[0]);
  16751. };
  16752. /**
  16753. * Gets the source code of the fragment shader associated with a specific webGL program
  16754. * @param program defines the program to use
  16755. * @returns a string containing the source code of the fragment shader associated with the program
  16756. */
  16757. Engine.prototype.getFragmentShaderSource = function (program) {
  16758. var shaders = this._gl.getAttachedShaders(program);
  16759. if (!shaders) {
  16760. return null;
  16761. }
  16762. return this._gl.getShaderSource(shaders[1]);
  16763. };
  16764. /**
  16765. * Get the current error code of the webGL context
  16766. * @returns the error code
  16767. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16768. */
  16769. Engine.prototype.getError = function () {
  16770. return this._gl.getError();
  16771. };
  16772. // FPS
  16773. /**
  16774. * Gets the current framerate
  16775. * @returns a number representing the framerate
  16776. */
  16777. Engine.prototype.getFps = function () {
  16778. return this._fps;
  16779. };
  16780. /**
  16781. * Gets the time spent between current and previous frame
  16782. * @returns a number representing the delta time in ms
  16783. */
  16784. Engine.prototype.getDeltaTime = function () {
  16785. return this._deltaTime;
  16786. };
  16787. Engine.prototype._measureFps = function () {
  16788. this._performanceMonitor.sampleFrame();
  16789. this._fps = this._performanceMonitor.averageFPS;
  16790. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16791. };
  16792. /** @hidden */
  16793. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16794. if (faceIndex === void 0) { faceIndex = -1; }
  16795. if (level === void 0) { level = 0; }
  16796. var gl = this._gl;
  16797. if (!this._dummyFramebuffer) {
  16798. var dummy = gl.createFramebuffer();
  16799. if (!dummy) {
  16800. throw new Error("Unable to create dummy framebuffer");
  16801. }
  16802. this._dummyFramebuffer = dummy;
  16803. }
  16804. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16805. if (faceIndex > -1) {
  16806. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16807. }
  16808. else {
  16809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16810. }
  16811. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16812. var buffer;
  16813. switch (readType) {
  16814. case gl.UNSIGNED_BYTE:
  16815. buffer = new Uint8Array(4 * width * height);
  16816. readType = gl.UNSIGNED_BYTE;
  16817. break;
  16818. default:
  16819. buffer = new Float32Array(4 * width * height);
  16820. readType = gl.FLOAT;
  16821. break;
  16822. }
  16823. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16824. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16825. return buffer;
  16826. };
  16827. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16828. if (this._webGLVersion > 1) {
  16829. return this._caps.colorBufferFloat;
  16830. }
  16831. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16832. };
  16833. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16834. if (this._webGLVersion > 1) {
  16835. return this._caps.colorBufferFloat;
  16836. }
  16837. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16838. };
  16839. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16840. Engine.prototype._canRenderToFramebuffer = function (type) {
  16841. var gl = this._gl;
  16842. //clear existing errors
  16843. while (gl.getError() !== gl.NO_ERROR) { }
  16844. var successful = true;
  16845. var texture = gl.createTexture();
  16846. gl.bindTexture(gl.TEXTURE_2D, texture);
  16847. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16850. var fb = gl.createFramebuffer();
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16853. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16854. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16855. successful = successful && (gl.getError() === gl.NO_ERROR);
  16856. //try render by clearing frame buffer's color buffer
  16857. if (successful) {
  16858. gl.clear(gl.COLOR_BUFFER_BIT);
  16859. successful = successful && (gl.getError() === gl.NO_ERROR);
  16860. }
  16861. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16862. if (successful) {
  16863. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16864. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16865. var readFormat = gl.RGBA;
  16866. var readType = gl.UNSIGNED_BYTE;
  16867. var buffer = new Uint8Array(4);
  16868. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16869. successful = successful && (gl.getError() === gl.NO_ERROR);
  16870. }
  16871. //clean up
  16872. gl.deleteTexture(texture);
  16873. gl.deleteFramebuffer(fb);
  16874. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16875. //clear accumulated errors
  16876. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16877. return successful;
  16878. };
  16879. /** @hidden */
  16880. Engine.prototype._getWebGLTextureType = function (type) {
  16881. if (type === Engine.TEXTURETYPE_FLOAT) {
  16882. return this._gl.FLOAT;
  16883. }
  16884. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16885. // Add Half Float Constant.
  16886. return this._gl.HALF_FLOAT_OES;
  16887. }
  16888. return this._gl.UNSIGNED_BYTE;
  16889. };
  16890. ;
  16891. Engine.prototype._getInternalFormat = function (format) {
  16892. var internalFormat = this._gl.RGBA;
  16893. switch (format) {
  16894. case Engine.TEXTUREFORMAT_ALPHA:
  16895. internalFormat = this._gl.ALPHA;
  16896. break;
  16897. case Engine.TEXTUREFORMAT_LUMINANCE:
  16898. internalFormat = this._gl.LUMINANCE;
  16899. break;
  16900. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16901. internalFormat = this._gl.LUMINANCE_ALPHA;
  16902. break;
  16903. case Engine.TEXTUREFORMAT_RGB:
  16904. internalFormat = this._gl.RGB;
  16905. break;
  16906. case Engine.TEXTUREFORMAT_RGBA:
  16907. internalFormat = this._gl.RGBA;
  16908. break;
  16909. case Engine.TEXTUREFORMAT_R:
  16910. internalFormat = this._gl.RED;
  16911. break;
  16912. case Engine.TEXTUREFORMAT_RG:
  16913. internalFormat = this._gl.RG;
  16914. break;
  16915. }
  16916. return internalFormat;
  16917. };
  16918. /** @hidden */
  16919. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16920. if (this._webGLVersion === 1) {
  16921. if (format !== undefined) {
  16922. switch (format) {
  16923. case Engine.TEXTUREFORMAT_LUMINANCE:
  16924. return this._gl.LUMINANCE;
  16925. case Engine.TEXTUREFORMAT_ALPHA:
  16926. return this._gl.ALPHA;
  16927. }
  16928. }
  16929. return this._gl.RGBA;
  16930. }
  16931. if (type === Engine.TEXTURETYPE_FLOAT) {
  16932. if (format !== undefined) {
  16933. switch (format) {
  16934. case Engine.TEXTUREFORMAT_R:
  16935. return this._gl.R32F;
  16936. case Engine.TEXTUREFORMAT_RG:
  16937. return this._gl.RG32F;
  16938. case Engine.TEXTUREFORMAT_RGB:
  16939. return this._gl.RGB32F;
  16940. }
  16941. }
  16942. return this._gl.RGBA32F;
  16943. }
  16944. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16945. if (format) {
  16946. switch (format) {
  16947. case Engine.TEXTUREFORMAT_R:
  16948. return this._gl.R16F;
  16949. case Engine.TEXTUREFORMAT_RG:
  16950. return this._gl.RG16F;
  16951. case Engine.TEXTUREFORMAT_RGB:
  16952. return this._gl.RGB16F;
  16953. }
  16954. }
  16955. return this._gl.RGBA16F;
  16956. }
  16957. if (format !== undefined) {
  16958. switch (format) {
  16959. case Engine.TEXTUREFORMAT_LUMINANCE:
  16960. return this._gl.LUMINANCE;
  16961. case Engine.TEXTUREFORMAT_RGB:
  16962. return this._gl.RGB;
  16963. case Engine.TEXTUREFORMAT_R:
  16964. return this._gl.R8;
  16965. case Engine.TEXTUREFORMAT_RG:
  16966. return this._gl.RG8;
  16967. case Engine.TEXTUREFORMAT_ALPHA:
  16968. return this._gl.ALPHA;
  16969. }
  16970. }
  16971. return this._gl.RGBA;
  16972. };
  16973. ;
  16974. /** @hidden */
  16975. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16976. if (type === Engine.TEXTURETYPE_FLOAT) {
  16977. return this._gl.RGBA32F;
  16978. }
  16979. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16980. return this._gl.RGBA16F;
  16981. }
  16982. return this._gl.RGBA8;
  16983. };
  16984. ;
  16985. // Transform feedback
  16986. /**
  16987. * Creates a webGL transform feedback object
  16988. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16989. * @returns the webGL transform feedback object
  16990. */
  16991. Engine.prototype.createTransformFeedback = function () {
  16992. return this._gl.createTransformFeedback();
  16993. };
  16994. /**
  16995. * Delete a webGL transform feedback object
  16996. * @param value defines the webGL transform feedback object to delete
  16997. */
  16998. Engine.prototype.deleteTransformFeedback = function (value) {
  16999. this._gl.deleteTransformFeedback(value);
  17000. };
  17001. /**
  17002. * Bind a webGL transform feedback object to the webgl context
  17003. * @param value defines the webGL transform feedback object to bind
  17004. */
  17005. Engine.prototype.bindTransformFeedback = function (value) {
  17006. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17007. };
  17008. /**
  17009. * Begins a transform feedback operation
  17010. * @param usePoints defines if points or triangles must be used
  17011. */
  17012. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17013. if (usePoints === void 0) { usePoints = true; }
  17014. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17015. };
  17016. /**
  17017. * Ends a transform feedback operation
  17018. */
  17019. Engine.prototype.endTransformFeedback = function () {
  17020. this._gl.endTransformFeedback();
  17021. };
  17022. /**
  17023. * Specify the varyings to use with transform feedback
  17024. * @param program defines the associated webGL program
  17025. * @param value defines the list of strings representing the varying names
  17026. */
  17027. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17028. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17029. };
  17030. /**
  17031. * Bind a webGL buffer for a transform feedback operation
  17032. * @param value defines the webGL buffer to bind
  17033. */
  17034. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17035. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17036. };
  17037. /** @hidden */
  17038. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17039. var _this = this;
  17040. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17041. this._activeRequests.push(request);
  17042. request.onCompleteObservable.add(function (request) {
  17043. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17044. });
  17045. return request;
  17046. };
  17047. /** @hidden */
  17048. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17049. var _this = this;
  17050. return new Promise(function (resolve, reject) {
  17051. _this._loadFile(url, function (data) {
  17052. resolve(data);
  17053. }, undefined, database, useArrayBuffer, function (request, exception) {
  17054. reject(exception);
  17055. });
  17056. });
  17057. };
  17058. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17059. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17060. var onload = function (data) {
  17061. loadedFiles[index] = data;
  17062. loadedFiles._internalCount++;
  17063. if (loadedFiles._internalCount === 6) {
  17064. onfinish(loadedFiles);
  17065. }
  17066. };
  17067. var onerror = function (request, exception) {
  17068. if (onErrorCallBack && request) {
  17069. onErrorCallBack(request.status + " " + request.statusText, exception);
  17070. }
  17071. };
  17072. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17073. };
  17074. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17075. if (onError === void 0) { onError = null; }
  17076. var loadedFiles = [];
  17077. loadedFiles._internalCount = 0;
  17078. for (var index = 0; index < 6; index++) {
  17079. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17080. }
  17081. };
  17082. // Statics
  17083. /**
  17084. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17085. * @returns true if the engine can be created
  17086. * @ignorenaming
  17087. */
  17088. Engine.isSupported = function () {
  17089. try {
  17090. var tempcanvas = document.createElement("canvas");
  17091. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17092. return gl != null && !!window.WebGLRenderingContext;
  17093. }
  17094. catch (e) {
  17095. return false;
  17096. }
  17097. };
  17098. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17099. Engine.ExceptionList = [
  17100. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17101. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17102. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17103. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17104. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17105. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17106. ];
  17107. /** Gets the list of created engines */
  17108. Engine.Instances = new Array();
  17109. // Const statics
  17110. /** Defines that alpha blending is disabled */
  17111. Engine.ALPHA_DISABLE = 0;
  17112. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17113. Engine.ALPHA_ADD = 1;
  17114. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17115. Engine.ALPHA_COMBINE = 2;
  17116. /** Defines that alpha blending to DEST - SRC * DEST */
  17117. Engine.ALPHA_SUBTRACT = 3;
  17118. /** Defines that alpha blending to SRC * DEST */
  17119. Engine.ALPHA_MULTIPLY = 4;
  17120. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17121. Engine.ALPHA_MAXIMIZED = 5;
  17122. /** Defines that alpha blending to SRC + DEST */
  17123. Engine.ALPHA_ONEONE = 6;
  17124. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17125. Engine.ALPHA_PREMULTIPLIED = 7;
  17126. /**
  17127. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17128. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17129. */
  17130. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17131. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17132. Engine.ALPHA_INTERPOLATE = 9;
  17133. /**
  17134. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17135. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17136. */
  17137. Engine.ALPHA_SCREENMODE = 10;
  17138. /** Defines that the ressource is not delayed*/
  17139. Engine.DELAYLOADSTATE_NONE = 0;
  17140. /** Defines that the ressource was successfully delay loaded */
  17141. Engine.DELAYLOADSTATE_LOADED = 1;
  17142. /** Defines that the ressource is currently delay loading */
  17143. Engine.DELAYLOADSTATE_LOADING = 2;
  17144. /** Defines that the ressource is delayed and has not started loading */
  17145. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17146. // Depht or Stencil test Constants.
  17147. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17148. Engine.NEVER = 0x0200;
  17149. /** 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 */
  17150. Engine.ALWAYS = 0x0207;
  17151. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17152. Engine.LESS = 0x0201;
  17153. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17154. Engine.EQUAL = 0x0202;
  17155. /** 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 */
  17156. Engine.LEQUAL = 0x0203;
  17157. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17158. Engine.GREATER = 0x0204;
  17159. /** 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 */
  17160. Engine.GEQUAL = 0x0206;
  17161. /** 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 */
  17162. Engine.NOTEQUAL = 0x0205;
  17163. // Stencil Actions Constants.
  17164. /** Passed to stencilOperation to specify that stencil value must be kept */
  17165. Engine.KEEP = 0x1E00;
  17166. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17167. Engine.REPLACE = 0x1E01;
  17168. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17169. Engine.INCR = 0x1E02;
  17170. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17171. Engine.DECR = 0x1E03;
  17172. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17173. Engine.INVERT = 0x150A;
  17174. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17175. Engine.INCR_WRAP = 0x8507;
  17176. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17177. Engine.DECR_WRAP = 0x8508;
  17178. /** Texture is not repeating outside of 0..1 UVs */
  17179. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17180. /** Texture is repeating outside of 0..1 UVs */
  17181. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17182. /** Texture is repeating and mirrored */
  17183. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17184. /** ALPHA */
  17185. Engine.TEXTUREFORMAT_ALPHA = 0;
  17186. /** LUMINANCE */
  17187. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17188. /** LUMINANCE_ALPHA */
  17189. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17190. /** RGB */
  17191. Engine.TEXTUREFORMAT_RGB = 4;
  17192. /** RGBA */
  17193. Engine.TEXTUREFORMAT_RGBA = 5;
  17194. /** R */
  17195. Engine.TEXTUREFORMAT_R = 6;
  17196. /** RG */
  17197. Engine.TEXTUREFORMAT_RG = 7;
  17198. /** UNSIGNED_INT */
  17199. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17200. /** FLOAT */
  17201. Engine.TEXTURETYPE_FLOAT = 1;
  17202. /** HALF_FLOAT */
  17203. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17204. /** nearest is mag = nearest and min = nearest and mip = linear */
  17205. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17206. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17207. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17208. /** Trilinear is mag = linear and min = linear and mip = linear */
  17209. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17210. /** nearest is mag = nearest and min = nearest and mip = linear */
  17211. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17212. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17213. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17214. /** Trilinear is mag = linear and min = linear and mip = linear */
  17215. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17216. /** mag = nearest and min = nearest and mip = nearest */
  17217. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17218. /** mag = nearest and min = linear and mip = nearest */
  17219. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17220. /** mag = nearest and min = linear and mip = linear */
  17221. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17222. /** mag = nearest and min = linear and mip = none */
  17223. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17224. /** mag = nearest and min = nearest and mip = none */
  17225. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17226. /** mag = linear and min = nearest and mip = nearest */
  17227. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17228. /** mag = linear and min = nearest and mip = linear */
  17229. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17230. /** mag = linear and min = linear and mip = none */
  17231. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17232. /** mag = linear and min = nearest and mip = none */
  17233. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17234. /** Explicit coordinates mode */
  17235. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17236. /** Spherical coordinates mode */
  17237. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17238. /** Planar coordinates mode */
  17239. Engine.TEXTURE_PLANAR_MODE = 2;
  17240. /** Cubic coordinates mode */
  17241. Engine.TEXTURE_CUBIC_MODE = 3;
  17242. /** Projection coordinates mode */
  17243. Engine.TEXTURE_PROJECTION_MODE = 4;
  17244. /** Skybox coordinates mode */
  17245. Engine.TEXTURE_SKYBOX_MODE = 5;
  17246. /** Inverse Cubic coordinates mode */
  17247. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17248. /** Equirectangular coordinates mode */
  17249. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17250. /** Equirectangular Fixed coordinates mode */
  17251. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17252. /** Equirectangular Fixed Mirrored coordinates mode */
  17253. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17254. // Texture rescaling mode
  17255. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17256. Engine.SCALEMODE_FLOOR = 1;
  17257. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17258. Engine.SCALEMODE_NEAREST = 2;
  17259. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17260. Engine.SCALEMODE_CEILING = 3;
  17261. // Updatable statics so stick with vars here
  17262. /**
  17263. * Gets or sets the epsilon value used by collision engine
  17264. */
  17265. Engine.CollisionsEpsilon = 0.001;
  17266. /**
  17267. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17268. */
  17269. Engine.CodeRepository = "src/";
  17270. /**
  17271. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17272. */
  17273. Engine.ShadersRepository = "src/Shaders/";
  17274. return Engine;
  17275. }());
  17276. BABYLON.Engine = Engine;
  17277. })(BABYLON || (BABYLON = {}));
  17278. //# sourceMappingURL=babylon.engine.js.map
  17279. var BABYLON;
  17280. (function (BABYLON) {
  17281. /**
  17282. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17283. */
  17284. var Node = /** @class */ (function () {
  17285. /**
  17286. * Creates a new Node
  17287. * @param {string} name - the name and id to be given to this node
  17288. * @param {BABYLON.Scene} the scene this node will be added to
  17289. */
  17290. function Node(name, scene) {
  17291. if (scene === void 0) { scene = null; }
  17292. /**
  17293. * Gets or sets a string used to store user defined state for the node
  17294. */
  17295. this.state = "";
  17296. /**
  17297. * Gets or sets an object used to store user defined information for the node
  17298. */
  17299. this.metadata = null;
  17300. /**
  17301. * Gets or sets a boolean used to define if the node must be serialized
  17302. */
  17303. this.doNotSerialize = false;
  17304. /** @hidden */
  17305. this._isDisposed = false;
  17306. /**
  17307. * Gets a list of Animations associated with the node
  17308. */
  17309. this.animations = new Array();
  17310. this._ranges = {};
  17311. this._isEnabled = true;
  17312. this._isReady = true;
  17313. /** @hidden */
  17314. this._currentRenderId = -1;
  17315. this._parentRenderId = -1;
  17316. this._childRenderId = -1;
  17317. this._animationPropertiesOverride = null;
  17318. /**
  17319. * An event triggered when the mesh is disposed
  17320. */
  17321. this.onDisposeObservable = new BABYLON.Observable();
  17322. // Behaviors
  17323. this._behaviors = new Array();
  17324. this.name = name;
  17325. this.id = name;
  17326. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17327. this.uniqueId = this._scene.getUniqueId();
  17328. this._initCache();
  17329. }
  17330. /**
  17331. * Add a new node constructor
  17332. * @param type defines the type name of the node to construct
  17333. * @param constructorFunc defines the constructor function
  17334. */
  17335. Node.AddNodeConstructor = function (type, constructorFunc) {
  17336. this._NodeConstructors[type] = constructorFunc;
  17337. };
  17338. /**
  17339. * Returns a node constructor based on type name
  17340. * @param type defines the type name
  17341. * @param name defines the new node name
  17342. * @param scene defines the hosting scene
  17343. * @param options defines optional options to transmit to constructors
  17344. * @returns the new constructor or null
  17345. */
  17346. Node.Construct = function (type, name, scene, options) {
  17347. var constructorFunc = this._NodeConstructors[type];
  17348. if (!constructorFunc) {
  17349. return null;
  17350. }
  17351. return constructorFunc(name, scene, options);
  17352. };
  17353. /**
  17354. * Gets a boolean indicating if the node has been disposed
  17355. * @returns true if the node was disposed
  17356. */
  17357. Node.prototype.isDisposed = function () {
  17358. return this._isDisposed;
  17359. };
  17360. Object.defineProperty(Node.prototype, "parent", {
  17361. get: function () {
  17362. return this._parentNode;
  17363. },
  17364. /**
  17365. * Gets or sets the parent of the node
  17366. */
  17367. set: function (parent) {
  17368. if (this._parentNode === parent) {
  17369. return;
  17370. }
  17371. // Remove self from list of children of parent
  17372. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17373. var index = this._parentNode._children.indexOf(this);
  17374. if (index !== -1) {
  17375. this._parentNode._children.splice(index, 1);
  17376. }
  17377. }
  17378. // Store new parent
  17379. this._parentNode = parent;
  17380. // Add as child to new parent
  17381. if (this._parentNode) {
  17382. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17383. this._parentNode._children = new Array();
  17384. }
  17385. this._parentNode._children.push(this);
  17386. }
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17392. /**
  17393. * Gets or sets the animation properties override
  17394. */
  17395. get: function () {
  17396. if (!this._animationPropertiesOverride) {
  17397. return this._scene.animationPropertiesOverride;
  17398. }
  17399. return this._animationPropertiesOverride;
  17400. },
  17401. set: function (value) {
  17402. this._animationPropertiesOverride = value;
  17403. },
  17404. enumerable: true,
  17405. configurable: true
  17406. });
  17407. /**
  17408. * Gets a string idenfifying the name of the class
  17409. * @returns "Node" string
  17410. */
  17411. Node.prototype.getClassName = function () {
  17412. return "Node";
  17413. };
  17414. Object.defineProperty(Node.prototype, "onDispose", {
  17415. /**
  17416. * Sets a callback that will be raised when the node will be disposed
  17417. */
  17418. set: function (callback) {
  17419. if (this._onDisposeObserver) {
  17420. this.onDisposeObservable.remove(this._onDisposeObserver);
  17421. }
  17422. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. /**
  17428. * Gets the scene of the node
  17429. * @returns a {BABYLON.Scene}
  17430. */
  17431. Node.prototype.getScene = function () {
  17432. return this._scene;
  17433. };
  17434. /**
  17435. * Gets the engine of the node
  17436. * @returns a {BABYLON.Engine}
  17437. */
  17438. Node.prototype.getEngine = function () {
  17439. return this._scene.getEngine();
  17440. };
  17441. /**
  17442. * Attach a behavior to the node
  17443. * @see http://doc.babylonjs.com/features/behaviour
  17444. * @param behavior defines the behavior to attach
  17445. * @returns the current Node
  17446. */
  17447. Node.prototype.addBehavior = function (behavior) {
  17448. var _this = this;
  17449. var index = this._behaviors.indexOf(behavior);
  17450. if (index !== -1) {
  17451. return this;
  17452. }
  17453. behavior.init();
  17454. if (this._scene.isLoading) {
  17455. // We defer the attach when the scene will be loaded
  17456. this._scene.onDataLoadedObservable.addOnce(function () {
  17457. behavior.attach(_this);
  17458. });
  17459. }
  17460. else {
  17461. behavior.attach(this);
  17462. }
  17463. this._behaviors.push(behavior);
  17464. return this;
  17465. };
  17466. /**
  17467. * Remove an attached behavior
  17468. * @see http://doc.babylonjs.com/features/behaviour
  17469. * @param behavior defines the behavior to attach
  17470. * @returns the current Node
  17471. */
  17472. Node.prototype.removeBehavior = function (behavior) {
  17473. var index = this._behaviors.indexOf(behavior);
  17474. if (index === -1) {
  17475. return this;
  17476. }
  17477. this._behaviors[index].detach();
  17478. this._behaviors.splice(index, 1);
  17479. return this;
  17480. };
  17481. Object.defineProperty(Node.prototype, "behaviors", {
  17482. /**
  17483. * Gets the list of attached behaviors
  17484. * @see http://doc.babylonjs.com/features/behaviour
  17485. */
  17486. get: function () {
  17487. return this._behaviors;
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. /**
  17493. * Gets an attached behavior by name
  17494. * @param name defines the name of the behavior to look for
  17495. * @see http://doc.babylonjs.com/features/behaviour
  17496. * @returns null if behavior was not found else the requested behavior
  17497. */
  17498. Node.prototype.getBehaviorByName = function (name) {
  17499. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17500. var behavior = _a[_i];
  17501. if (behavior.name === name) {
  17502. return behavior;
  17503. }
  17504. }
  17505. return null;
  17506. };
  17507. /**
  17508. * Returns the world matrix of the node
  17509. * @returns a matrix containing the node's world matrix
  17510. */
  17511. Node.prototype.getWorldMatrix = function () {
  17512. return BABYLON.Matrix.Identity();
  17513. };
  17514. /** @hidden */
  17515. Node.prototype._getWorldMatrixDeterminant = function () {
  17516. return 1;
  17517. };
  17518. // override it in derived class if you add new variables to the cache
  17519. // and call the parent class method
  17520. /** @hidden */
  17521. Node.prototype._initCache = function () {
  17522. this._cache = {};
  17523. this._cache.parent = undefined;
  17524. };
  17525. /** @hidden */
  17526. Node.prototype.updateCache = function (force) {
  17527. if (!force && this.isSynchronized())
  17528. return;
  17529. this._cache.parent = this.parent;
  17530. this._updateCache();
  17531. };
  17532. // override it in derived class if you add new variables to the cache
  17533. // and call the parent class method if !ignoreParentClass
  17534. /** @hidden */
  17535. Node.prototype._updateCache = function (ignoreParentClass) {
  17536. };
  17537. // override it in derived class if you add new variables to the cache
  17538. /** @hidden */
  17539. Node.prototype._isSynchronized = function () {
  17540. return true;
  17541. };
  17542. /** @hidden */
  17543. Node.prototype._markSyncedWithParent = function () {
  17544. if (this.parent) {
  17545. this._parentRenderId = this.parent._childRenderId;
  17546. }
  17547. };
  17548. /** @hidden */
  17549. Node.prototype.isSynchronizedWithParent = function () {
  17550. if (!this.parent) {
  17551. return true;
  17552. }
  17553. if (this._parentRenderId !== this.parent._childRenderId) {
  17554. return false;
  17555. }
  17556. return this.parent.isSynchronized();
  17557. };
  17558. /** @hidden */
  17559. Node.prototype.isSynchronized = function (updateCache) {
  17560. var check = this.hasNewParent();
  17561. check = check || !this.isSynchronizedWithParent();
  17562. check = check || !this._isSynchronized();
  17563. if (updateCache)
  17564. this.updateCache(true);
  17565. return !check;
  17566. };
  17567. /** @hidden */
  17568. Node.prototype.hasNewParent = function (update) {
  17569. if (this._cache.parent === this.parent)
  17570. return false;
  17571. if (update)
  17572. this._cache.parent = this.parent;
  17573. return true;
  17574. };
  17575. /**
  17576. * Is this node ready to be used/rendered
  17577. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17578. * @return true if the node is ready
  17579. */
  17580. Node.prototype.isReady = function (completeCheck) {
  17581. if (completeCheck === void 0) { completeCheck = false; }
  17582. return this._isReady;
  17583. };
  17584. /**
  17585. * Is this node enabled?
  17586. * 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
  17587. * @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
  17588. * @return whether this node (and its parent) is enabled
  17589. */
  17590. Node.prototype.isEnabled = function (checkAncestors) {
  17591. if (checkAncestors === void 0) { checkAncestors = true; }
  17592. if (checkAncestors === false) {
  17593. return this._isEnabled;
  17594. }
  17595. if (this._isEnabled === false) {
  17596. return false;
  17597. }
  17598. if (this.parent !== undefined && this.parent !== null) {
  17599. return this.parent.isEnabled(checkAncestors);
  17600. }
  17601. return true;
  17602. };
  17603. /**
  17604. * Set the enabled state of this node
  17605. * @param value defines the new enabled state
  17606. */
  17607. Node.prototype.setEnabled = function (value) {
  17608. this._isEnabled = value;
  17609. };
  17610. /**
  17611. * Is this node a descendant of the given node?
  17612. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17613. * @param ancestor defines the parent node to inspect
  17614. * @returns a boolean indicating if this node is a descendant of the given node
  17615. */
  17616. Node.prototype.isDescendantOf = function (ancestor) {
  17617. if (this.parent) {
  17618. if (this.parent === ancestor) {
  17619. return true;
  17620. }
  17621. return this.parent.isDescendantOf(ancestor);
  17622. }
  17623. return false;
  17624. };
  17625. /** @hidden */
  17626. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17627. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17628. if (!this._children) {
  17629. return;
  17630. }
  17631. for (var index = 0; index < this._children.length; index++) {
  17632. var item = this._children[index];
  17633. if (!predicate || predicate(item)) {
  17634. results.push(item);
  17635. }
  17636. if (!directDescendantsOnly) {
  17637. item._getDescendants(results, false, predicate);
  17638. }
  17639. }
  17640. };
  17641. /**
  17642. * Will return all nodes that have this node as ascendant
  17643. * @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
  17644. * @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
  17645. * @return all children nodes of all types
  17646. */
  17647. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17648. var results = new Array();
  17649. this._getDescendants(results, directDescendantsOnly, predicate);
  17650. return results;
  17651. };
  17652. /**
  17653. * Get all child-meshes of this node
  17654. * @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
  17655. * @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
  17656. * @returns an array of {BABYLON.AbstractMesh}
  17657. */
  17658. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17659. var results = [];
  17660. this._getDescendants(results, directDescendantsOnly, function (node) {
  17661. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17662. });
  17663. return results;
  17664. };
  17665. /**
  17666. * Get all child-transformNodes of this node
  17667. * @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
  17668. * @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
  17669. * @returns an array of {BABYLON.TransformNode}
  17670. */
  17671. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17672. var results = [];
  17673. this._getDescendants(results, directDescendantsOnly, function (node) {
  17674. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17675. });
  17676. return results;
  17677. };
  17678. /**
  17679. * Get all direct children of this node
  17680. * @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
  17681. * @returns an array of {BABYLON.Node}
  17682. */
  17683. Node.prototype.getChildren = function (predicate) {
  17684. return this.getDescendants(true, predicate);
  17685. };
  17686. /** @hidden */
  17687. Node.prototype._setReady = function (state) {
  17688. if (state === this._isReady) {
  17689. return;
  17690. }
  17691. if (!state) {
  17692. this._isReady = false;
  17693. return;
  17694. }
  17695. if (this.onReady) {
  17696. this.onReady(this);
  17697. }
  17698. this._isReady = true;
  17699. };
  17700. /**
  17701. * Get an animation by name
  17702. * @param name defines the name of the animation to look for
  17703. * @returns null if not found else the requested animation
  17704. */
  17705. Node.prototype.getAnimationByName = function (name) {
  17706. for (var i = 0; i < this.animations.length; i++) {
  17707. var animation = this.animations[i];
  17708. if (animation.name === name) {
  17709. return animation;
  17710. }
  17711. }
  17712. return null;
  17713. };
  17714. /**
  17715. * Creates an animation range for this node
  17716. * @param name defines the name of the range
  17717. * @param from defines the starting key
  17718. * @param to defines the end key
  17719. */
  17720. Node.prototype.createAnimationRange = function (name, from, to) {
  17721. // check name not already in use
  17722. if (!this._ranges[name]) {
  17723. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17724. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17725. if (this.animations[i]) {
  17726. this.animations[i].createRange(name, from, to);
  17727. }
  17728. }
  17729. }
  17730. };
  17731. /**
  17732. * Delete a specific animation range
  17733. * @param name defines the name of the range to delete
  17734. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17735. */
  17736. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17737. if (deleteFrames === void 0) { deleteFrames = true; }
  17738. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17739. if (this.animations[i]) {
  17740. this.animations[i].deleteRange(name, deleteFrames);
  17741. }
  17742. }
  17743. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17744. };
  17745. /**
  17746. * Get an animation range by name
  17747. * @param name defines the name of the animation range to look for
  17748. * @returns null if not found else the requested animation range
  17749. */
  17750. Node.prototype.getAnimationRange = function (name) {
  17751. return this._ranges[name];
  17752. };
  17753. /**
  17754. * Will start the animation sequence
  17755. * @param name defines the range frames for animation sequence
  17756. * @param loop defines if the animation should loop (false by default)
  17757. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17758. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17759. * @returns the object created for this animation. If range does not exist, it will return null
  17760. */
  17761. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17762. var range = this.getAnimationRange(name);
  17763. if (!range) {
  17764. return null;
  17765. }
  17766. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17767. };
  17768. /**
  17769. * Serialize animation ranges into a JSON compatible object
  17770. * @returns serialization object
  17771. */
  17772. Node.prototype.serializeAnimationRanges = function () {
  17773. var serializationRanges = [];
  17774. for (var name in this._ranges) {
  17775. var localRange = this._ranges[name];
  17776. if (!localRange) {
  17777. continue;
  17778. }
  17779. var range = {};
  17780. range.name = name;
  17781. range.from = localRange.from;
  17782. range.to = localRange.to;
  17783. serializationRanges.push(range);
  17784. }
  17785. return serializationRanges;
  17786. };
  17787. /**
  17788. * Computes the world matrix of the node
  17789. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17790. * @returns the world matrix
  17791. */
  17792. Node.prototype.computeWorldMatrix = function (force) {
  17793. return BABYLON.Matrix.Identity();
  17794. };
  17795. /**
  17796. * Releases resources associated with this node.
  17797. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17798. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17799. */
  17800. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17801. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17802. if (!doNotRecurse) {
  17803. var nodes = this.getDescendants(true);
  17804. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17805. var node = nodes_1[_i];
  17806. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17807. }
  17808. }
  17809. else {
  17810. var transformNodes = this.getChildTransformNodes(true);
  17811. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17812. var transformNode = transformNodes_1[_a];
  17813. transformNode.parent = null;
  17814. transformNode.computeWorldMatrix(true);
  17815. }
  17816. }
  17817. this.parent = null;
  17818. // Callback
  17819. this.onDisposeObservable.notifyObservers(this);
  17820. this.onDisposeObservable.clear();
  17821. // Behaviors
  17822. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17823. var behavior = _c[_b];
  17824. behavior.detach();
  17825. }
  17826. this._behaviors = [];
  17827. this._isDisposed = true;
  17828. };
  17829. /**
  17830. * Parse animation range data from a serialization object and store them into a given node
  17831. * @param node defines where to store the animation ranges
  17832. * @param parsedNode defines the serialization object to read data from
  17833. * @param scene defines the hosting scene
  17834. */
  17835. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17836. if (parsedNode.ranges) {
  17837. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17838. var data = parsedNode.ranges[index];
  17839. node.createAnimationRange(data.name, data.from, data.to);
  17840. }
  17841. }
  17842. };
  17843. Node._NodeConstructors = {};
  17844. __decorate([
  17845. BABYLON.serialize()
  17846. ], Node.prototype, "name", void 0);
  17847. __decorate([
  17848. BABYLON.serialize()
  17849. ], Node.prototype, "id", void 0);
  17850. __decorate([
  17851. BABYLON.serialize()
  17852. ], Node.prototype, "uniqueId", void 0);
  17853. __decorate([
  17854. BABYLON.serialize()
  17855. ], Node.prototype, "state", void 0);
  17856. __decorate([
  17857. BABYLON.serialize()
  17858. ], Node.prototype, "metadata", void 0);
  17859. return Node;
  17860. }());
  17861. BABYLON.Node = Node;
  17862. })(BABYLON || (BABYLON = {}));
  17863. //# sourceMappingURL=babylon.node.js.map
  17864. var BABYLON;
  17865. (function (BABYLON) {
  17866. var BoundingSphere = /** @class */ (function () {
  17867. /**
  17868. * Creates a new bounding sphere
  17869. * @param min defines the minimum vector (in local space)
  17870. * @param max defines the maximum vector (in local space)
  17871. */
  17872. function BoundingSphere(min, max) {
  17873. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17874. this.reConstruct(min, max);
  17875. }
  17876. /**
  17877. * Recreates the entire bounding sphere from scratch
  17878. * @param min defines the new minimum vector (in local space)
  17879. * @param max defines the new maximum vector (in local space)
  17880. */
  17881. BoundingSphere.prototype.reConstruct = function (min, max) {
  17882. this.minimum = min.clone();
  17883. this.maximum = max.clone();
  17884. var distance = BABYLON.Vector3.Distance(min, max);
  17885. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17886. this.radius = distance * 0.5;
  17887. this.centerWorld = BABYLON.Vector3.Zero();
  17888. this._update(BABYLON.Matrix.Identity());
  17889. };
  17890. /**
  17891. * Scale the current bounding sphere by applying a scale factor
  17892. * @param factor defines the scale factor to apply
  17893. * @returns the current bounding box
  17894. */
  17895. BoundingSphere.prototype.scale = function (factor) {
  17896. var newRadius = this.radius * factor;
  17897. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17898. var min = this.center.subtract(newRadiusVector);
  17899. var max = this.center.add(newRadiusVector);
  17900. this.reConstruct(min, max);
  17901. return this;
  17902. };
  17903. // Methods
  17904. BoundingSphere.prototype._update = function (world) {
  17905. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17906. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17907. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17908. };
  17909. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17910. for (var i = 0; i < 6; i++) {
  17911. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17912. return false;
  17913. }
  17914. return true;
  17915. };
  17916. BoundingSphere.prototype.intersectsPoint = function (point) {
  17917. var x = this.centerWorld.x - point.x;
  17918. var y = this.centerWorld.y - point.y;
  17919. var z = this.centerWorld.z - point.z;
  17920. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17921. if (this.radiusWorld < distance)
  17922. return false;
  17923. return true;
  17924. };
  17925. // Statics
  17926. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17927. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17928. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17929. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17930. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17931. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17932. return false;
  17933. return true;
  17934. };
  17935. return BoundingSphere;
  17936. }());
  17937. BABYLON.BoundingSphere = BoundingSphere;
  17938. })(BABYLON || (BABYLON = {}));
  17939. //# sourceMappingURL=babylon.boundingSphere.js.map
  17940. var BABYLON;
  17941. (function (BABYLON) {
  17942. var BoundingBox = /** @class */ (function () {
  17943. /**
  17944. * Creates a new bounding box
  17945. * @param min defines the minimum vector (in local space)
  17946. * @param max defines the maximum vector (in local space)
  17947. */
  17948. function BoundingBox(min, max) {
  17949. this.vectorsWorld = new Array();
  17950. this.reConstruct(min, max);
  17951. }
  17952. // Methods
  17953. /**
  17954. * Recreates the entire bounding box from scratch
  17955. * @param min defines the new minimum vector (in local space)
  17956. * @param max defines the new maximum vector (in local space)
  17957. */
  17958. BoundingBox.prototype.reConstruct = function (min, max) {
  17959. this.minimum = min.clone();
  17960. this.maximum = max.clone();
  17961. // Bounding vectors
  17962. this.vectors = new Array();
  17963. this.vectors.push(this.minimum.clone());
  17964. this.vectors.push(this.maximum.clone());
  17965. this.vectors.push(this.minimum.clone());
  17966. this.vectors[2].x = this.maximum.x;
  17967. this.vectors.push(this.minimum.clone());
  17968. this.vectors[3].y = this.maximum.y;
  17969. this.vectors.push(this.minimum.clone());
  17970. this.vectors[4].z = this.maximum.z;
  17971. this.vectors.push(this.maximum.clone());
  17972. this.vectors[5].z = this.minimum.z;
  17973. this.vectors.push(this.maximum.clone());
  17974. this.vectors[6].x = this.minimum.x;
  17975. this.vectors.push(this.maximum.clone());
  17976. this.vectors[7].y = this.minimum.y;
  17977. // OBB
  17978. this.center = this.maximum.add(this.minimum).scale(0.5);
  17979. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17980. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17981. // World
  17982. for (var index = 0; index < this.vectors.length; index++) {
  17983. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17984. }
  17985. this.minimumWorld = BABYLON.Vector3.Zero();
  17986. this.maximumWorld = BABYLON.Vector3.Zero();
  17987. this.centerWorld = BABYLON.Vector3.Zero();
  17988. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17989. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17990. };
  17991. /**
  17992. * Scale the current bounding box by applying a scale factor
  17993. * @param factor defines the scale factor to apply
  17994. * @returns the current bounding box
  17995. */
  17996. BoundingBox.prototype.scale = function (factor) {
  17997. var diff = this.maximum.subtract(this.minimum);
  17998. var distance = diff.length() * factor;
  17999. diff.normalize();
  18000. var newRadius = diff.scale(distance / 2);
  18001. var min = this.center.subtract(newRadius);
  18002. var max = this.center.add(newRadius);
  18003. this.reConstruct(min, max);
  18004. return this;
  18005. };
  18006. BoundingBox.prototype.getWorldMatrix = function () {
  18007. return this._worldMatrix;
  18008. };
  18009. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18010. this._worldMatrix.copyFrom(matrix);
  18011. return this;
  18012. };
  18013. BoundingBox.prototype._update = function (world) {
  18014. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18015. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18016. for (var index = 0; index < this.vectors.length; index++) {
  18017. var v = this.vectorsWorld[index];
  18018. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18019. if (v.x < this.minimumWorld.x)
  18020. this.minimumWorld.x = v.x;
  18021. if (v.y < this.minimumWorld.y)
  18022. this.minimumWorld.y = v.y;
  18023. if (v.z < this.minimumWorld.z)
  18024. this.minimumWorld.z = v.z;
  18025. if (v.x > this.maximumWorld.x)
  18026. this.maximumWorld.x = v.x;
  18027. if (v.y > this.maximumWorld.y)
  18028. this.maximumWorld.y = v.y;
  18029. if (v.z > this.maximumWorld.z)
  18030. this.maximumWorld.z = v.z;
  18031. }
  18032. // Extend
  18033. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18034. this.extendSizeWorld.scaleInPlace(0.5);
  18035. // OBB
  18036. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18037. this.centerWorld.scaleInPlace(0.5);
  18038. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18039. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18040. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18041. this._worldMatrix = world;
  18042. };
  18043. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18044. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18045. };
  18046. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18047. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18048. };
  18049. BoundingBox.prototype.intersectsPoint = function (point) {
  18050. var delta = -BABYLON.Epsilon;
  18051. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18052. return false;
  18053. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18054. return false;
  18055. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18056. return false;
  18057. return true;
  18058. };
  18059. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18060. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18061. };
  18062. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18063. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18064. return false;
  18065. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18066. return false;
  18067. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18068. return false;
  18069. return true;
  18070. };
  18071. // Statics
  18072. BoundingBox.Intersects = function (box0, box1) {
  18073. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18074. return false;
  18075. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18076. return false;
  18077. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18078. return false;
  18079. return true;
  18080. };
  18081. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18082. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18083. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18084. return (num <= (sphereRadius * sphereRadius));
  18085. };
  18086. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18087. for (var p = 0; p < 6; p++) {
  18088. for (var i = 0; i < 8; i++) {
  18089. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18090. return false;
  18091. }
  18092. }
  18093. }
  18094. return true;
  18095. };
  18096. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18097. for (var p = 0; p < 6; p++) {
  18098. var inCount = 8;
  18099. for (var i = 0; i < 8; i++) {
  18100. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18101. --inCount;
  18102. }
  18103. else {
  18104. break;
  18105. }
  18106. }
  18107. if (inCount === 0)
  18108. return false;
  18109. }
  18110. return true;
  18111. };
  18112. return BoundingBox;
  18113. }());
  18114. BABYLON.BoundingBox = BoundingBox;
  18115. })(BABYLON || (BABYLON = {}));
  18116. //# sourceMappingURL=babylon.boundingBox.js.map
  18117. var BABYLON;
  18118. (function (BABYLON) {
  18119. var computeBoxExtents = function (axis, box) {
  18120. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18121. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18122. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18123. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18124. var r = r0 + r1 + r2;
  18125. return {
  18126. min: p - r,
  18127. max: p + r
  18128. };
  18129. };
  18130. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18131. var axisOverlap = function (axis, box0, box1) {
  18132. var result0 = computeBoxExtents(axis, box0);
  18133. var result1 = computeBoxExtents(axis, box1);
  18134. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18135. };
  18136. var BoundingInfo = /** @class */ (function () {
  18137. function BoundingInfo(minimum, maximum) {
  18138. this.minimum = minimum;
  18139. this.maximum = maximum;
  18140. this._isLocked = false;
  18141. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18142. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18143. }
  18144. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18145. get: function () {
  18146. return this._isLocked;
  18147. },
  18148. set: function (value) {
  18149. this._isLocked = value;
  18150. },
  18151. enumerable: true,
  18152. configurable: true
  18153. });
  18154. // Methods
  18155. BoundingInfo.prototype.update = function (world) {
  18156. if (this._isLocked) {
  18157. return;
  18158. }
  18159. this.boundingBox._update(world);
  18160. this.boundingSphere._update(world);
  18161. };
  18162. /**
  18163. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18164. * @param center New center of the bounding info
  18165. * @param extend New extend of the bounding info
  18166. */
  18167. BoundingInfo.prototype.centerOn = function (center, extend) {
  18168. this.minimum = center.subtract(extend);
  18169. this.maximum = center.add(extend);
  18170. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18171. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18172. return this;
  18173. };
  18174. /**
  18175. * Scale the current bounding info by applying a scale factor
  18176. * @param factor defines the scale factor to apply
  18177. * @returns the current bounding info
  18178. */
  18179. BoundingInfo.prototype.scale = function (factor) {
  18180. this.boundingBox.scale(factor);
  18181. this.boundingSphere.scale(factor);
  18182. return this;
  18183. };
  18184. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18185. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18186. return false;
  18187. return this.boundingBox.isInFrustum(frustumPlanes);
  18188. };
  18189. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18190. /**
  18191. * Gets the world distance between the min and max points of the bounding box
  18192. */
  18193. get: function () {
  18194. var boundingBox = this.boundingBox;
  18195. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18196. return size.length();
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18202. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18203. };
  18204. BoundingInfo.prototype._checkCollision = function (collider) {
  18205. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18206. };
  18207. BoundingInfo.prototype.intersectsPoint = function (point) {
  18208. if (!this.boundingSphere.centerWorld) {
  18209. return false;
  18210. }
  18211. if (!this.boundingSphere.intersectsPoint(point)) {
  18212. return false;
  18213. }
  18214. if (!this.boundingBox.intersectsPoint(point)) {
  18215. return false;
  18216. }
  18217. return true;
  18218. };
  18219. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18220. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18221. return false;
  18222. }
  18223. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18224. return false;
  18225. }
  18226. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18227. return false;
  18228. }
  18229. if (!precise) {
  18230. return true;
  18231. }
  18232. var box0 = this.boundingBox;
  18233. var box1 = boundingInfo.boundingBox;
  18234. if (!axisOverlap(box0.directions[0], box0, box1))
  18235. return false;
  18236. if (!axisOverlap(box0.directions[1], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box0.directions[2], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box1.directions[0], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(box1.directions[1], box0, box1))
  18243. return false;
  18244. if (!axisOverlap(box1.directions[2], box0, box1))
  18245. return false;
  18246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18259. return false;
  18260. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18261. return false;
  18262. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18263. return false;
  18264. return true;
  18265. };
  18266. return BoundingInfo;
  18267. }());
  18268. BABYLON.BoundingInfo = BoundingInfo;
  18269. })(BABYLON || (BABYLON = {}));
  18270. //# sourceMappingURL=babylon.boundingInfo.js.map
  18271. var BABYLON;
  18272. (function (BABYLON) {
  18273. var TransformNode = /** @class */ (function (_super) {
  18274. __extends(TransformNode, _super);
  18275. function TransformNode(name, scene, isPure) {
  18276. if (scene === void 0) { scene = null; }
  18277. if (isPure === void 0) { isPure = true; }
  18278. var _this = _super.call(this, name, scene) || this;
  18279. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18280. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18281. _this._up = new BABYLON.Vector3(0, 1, 0);
  18282. _this._right = new BABYLON.Vector3(1, 0, 0);
  18283. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18284. // Properties
  18285. _this._rotation = BABYLON.Vector3.Zero();
  18286. _this._scaling = BABYLON.Vector3.One();
  18287. _this._isDirty = false;
  18288. /**
  18289. * Set the billboard mode. Default is 0.
  18290. *
  18291. * | Value | Type | Description |
  18292. * | --- | --- | --- |
  18293. * | 0 | BILLBOARDMODE_NONE | |
  18294. * | 1 | BILLBOARDMODE_X | |
  18295. * | 2 | BILLBOARDMODE_Y | |
  18296. * | 4 | BILLBOARDMODE_Z | |
  18297. * | 7 | BILLBOARDMODE_ALL | |
  18298. *
  18299. */
  18300. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18301. _this.scalingDeterminant = 1;
  18302. _this.infiniteDistance = false;
  18303. /**
  18304. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18305. * By default the system will update normals to compensate
  18306. */
  18307. _this.ignoreNonUniformScaling = false;
  18308. _this.position = BABYLON.Vector3.Zero();
  18309. _this._localWorld = BABYLON.Matrix.Zero();
  18310. _this._worldMatrix = BABYLON.Matrix.Zero();
  18311. _this._worldMatrixDeterminant = 0;
  18312. _this._absolutePosition = BABYLON.Vector3.Zero();
  18313. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18314. _this._postMultiplyPivotMatrix = false;
  18315. _this._isWorldMatrixFrozen = false;
  18316. /**
  18317. * An event triggered after the world matrix is updated
  18318. */
  18319. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18320. _this._nonUniformScaling = false;
  18321. if (isPure) {
  18322. _this.getScene().addTransformNode(_this);
  18323. }
  18324. return _this;
  18325. }
  18326. /**
  18327. * Gets a string idenfifying the name of the class
  18328. * @returns "TransformNode" string
  18329. */
  18330. TransformNode.prototype.getClassName = function () {
  18331. return "TransformNode";
  18332. };
  18333. Object.defineProperty(TransformNode.prototype, "rotation", {
  18334. /**
  18335. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18336. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18337. * Default : (0.0, 0.0, 0.0)
  18338. */
  18339. get: function () {
  18340. return this._rotation;
  18341. },
  18342. set: function (newRotation) {
  18343. this._rotation = newRotation;
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(TransformNode.prototype, "scaling", {
  18349. /**
  18350. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18351. * Default : (1.0, 1.0, 1.0)
  18352. */
  18353. get: function () {
  18354. return this._scaling;
  18355. },
  18356. /**
  18357. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18358. * Default : (1.0, 1.0, 1.0)
  18359. */
  18360. set: function (newScaling) {
  18361. this._scaling = newScaling;
  18362. },
  18363. enumerable: true,
  18364. configurable: true
  18365. });
  18366. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18367. /**
  18368. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18369. * It's null by default.
  18370. * 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)
  18371. */
  18372. get: function () {
  18373. return this._rotationQuaternion;
  18374. },
  18375. set: function (quaternion) {
  18376. this._rotationQuaternion = quaternion;
  18377. //reset the rotation vector.
  18378. if (quaternion && this.rotation.length()) {
  18379. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18380. }
  18381. },
  18382. enumerable: true,
  18383. configurable: true
  18384. });
  18385. Object.defineProperty(TransformNode.prototype, "forward", {
  18386. /**
  18387. * The forward direction of that transform in world space.
  18388. */
  18389. get: function () {
  18390. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. Object.defineProperty(TransformNode.prototype, "up", {
  18396. /**
  18397. * The up direction of that transform in world space.
  18398. */
  18399. get: function () {
  18400. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. Object.defineProperty(TransformNode.prototype, "right", {
  18406. /**
  18407. * The right direction of that transform in world space.
  18408. */
  18409. get: function () {
  18410. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18411. },
  18412. enumerable: true,
  18413. configurable: true
  18414. });
  18415. /**
  18416. * Returns the latest update of the World matrix
  18417. * Returns a Matrix.
  18418. */
  18419. TransformNode.prototype.getWorldMatrix = function () {
  18420. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18421. this.computeWorldMatrix();
  18422. }
  18423. return this._worldMatrix;
  18424. };
  18425. /** @hidden */
  18426. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18427. return this._worldMatrixDeterminant;
  18428. };
  18429. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18430. /**
  18431. * Returns directly the latest state of the mesh World matrix.
  18432. * A Matrix is returned.
  18433. */
  18434. get: function () {
  18435. return this._worldMatrix;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. /**
  18441. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18442. * Returns the TransformNode.
  18443. */
  18444. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18445. this._poseMatrix.copyFrom(matrix);
  18446. return this;
  18447. };
  18448. /**
  18449. * Returns the mesh Pose matrix.
  18450. * Returned object : Matrix
  18451. */
  18452. TransformNode.prototype.getPoseMatrix = function () {
  18453. return this._poseMatrix;
  18454. };
  18455. TransformNode.prototype._isSynchronized = function () {
  18456. if (this._isDirty) {
  18457. return false;
  18458. }
  18459. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18460. return false;
  18461. if (this._cache.pivotMatrixUpdated) {
  18462. return false;
  18463. }
  18464. if (this.infiniteDistance) {
  18465. return false;
  18466. }
  18467. if (!this._cache.position.equals(this.position))
  18468. return false;
  18469. if (this.rotationQuaternion) {
  18470. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18471. return false;
  18472. }
  18473. if (!this._cache.rotation.equals(this.rotation))
  18474. return false;
  18475. if (!this._cache.scaling.equals(this.scaling))
  18476. return false;
  18477. return true;
  18478. };
  18479. TransformNode.prototype._initCache = function () {
  18480. _super.prototype._initCache.call(this);
  18481. this._cache.localMatrixUpdated = false;
  18482. this._cache.position = BABYLON.Vector3.Zero();
  18483. this._cache.scaling = BABYLON.Vector3.Zero();
  18484. this._cache.rotation = BABYLON.Vector3.Zero();
  18485. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18486. this._cache.billboardMode = -1;
  18487. };
  18488. TransformNode.prototype.markAsDirty = function (property) {
  18489. if (property === "rotation") {
  18490. this.rotationQuaternion = null;
  18491. }
  18492. this._currentRenderId = Number.MAX_VALUE;
  18493. this._isDirty = true;
  18494. return this;
  18495. };
  18496. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18497. /**
  18498. * Returns the current mesh absolute position.
  18499. * Retuns a Vector3.
  18500. */
  18501. get: function () {
  18502. return this._absolutePosition;
  18503. },
  18504. enumerable: true,
  18505. configurable: true
  18506. });
  18507. /**
  18508. * Sets a new matrix to apply before all other transformation
  18509. * @param matrix defines the transform matrix
  18510. * @returns the current TransformNode
  18511. */
  18512. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18513. return this.setPivotMatrix(matrix, false);
  18514. };
  18515. /**
  18516. * Sets a new pivot matrix to the current node
  18517. * @param matrix defines the new pivot matrix to use
  18518. * @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
  18519. * @returns the current TransformNode
  18520. */
  18521. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18522. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18523. this._pivotMatrix = matrix.clone();
  18524. this._cache.pivotMatrixUpdated = true;
  18525. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18526. if (this._postMultiplyPivotMatrix) {
  18527. if (!this._pivotMatrixInverse) {
  18528. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18529. }
  18530. else {
  18531. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18532. }
  18533. }
  18534. return this;
  18535. };
  18536. /**
  18537. * Returns the mesh pivot matrix.
  18538. * Default : Identity.
  18539. * A Matrix is returned.
  18540. */
  18541. TransformNode.prototype.getPivotMatrix = function () {
  18542. return this._pivotMatrix;
  18543. };
  18544. /**
  18545. * Prevents the World matrix to be computed any longer.
  18546. * Returns the TransformNode.
  18547. */
  18548. TransformNode.prototype.freezeWorldMatrix = function () {
  18549. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18550. this.computeWorldMatrix(true);
  18551. this._isWorldMatrixFrozen = true;
  18552. return this;
  18553. };
  18554. /**
  18555. * Allows back the World matrix computation.
  18556. * Returns the TransformNode.
  18557. */
  18558. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18559. this._isWorldMatrixFrozen = false;
  18560. this.computeWorldMatrix(true);
  18561. return this;
  18562. };
  18563. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18564. /**
  18565. * True if the World matrix has been frozen.
  18566. * Returns a boolean.
  18567. */
  18568. get: function () {
  18569. return this._isWorldMatrixFrozen;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. /**
  18575. * Retuns the mesh absolute position in the World.
  18576. * Returns a Vector3.
  18577. */
  18578. TransformNode.prototype.getAbsolutePosition = function () {
  18579. this.computeWorldMatrix();
  18580. return this._absolutePosition;
  18581. };
  18582. /**
  18583. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18584. * Returns the TransformNode.
  18585. */
  18586. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18587. if (!absolutePosition) {
  18588. return this;
  18589. }
  18590. var absolutePositionX;
  18591. var absolutePositionY;
  18592. var absolutePositionZ;
  18593. if (absolutePosition.x === undefined) {
  18594. if (arguments.length < 3) {
  18595. return this;
  18596. }
  18597. absolutePositionX = arguments[0];
  18598. absolutePositionY = arguments[1];
  18599. absolutePositionZ = arguments[2];
  18600. }
  18601. else {
  18602. absolutePositionX = absolutePosition.x;
  18603. absolutePositionY = absolutePosition.y;
  18604. absolutePositionZ = absolutePosition.z;
  18605. }
  18606. if (this.parent) {
  18607. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18608. invertParentWorldMatrix.invert();
  18609. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18610. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18611. }
  18612. else {
  18613. this.position.x = absolutePositionX;
  18614. this.position.y = absolutePositionY;
  18615. this.position.z = absolutePositionZ;
  18616. }
  18617. return this;
  18618. };
  18619. /**
  18620. * Sets the mesh position in its local space.
  18621. * Returns the TransformNode.
  18622. */
  18623. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18624. this.computeWorldMatrix();
  18625. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18626. return this;
  18627. };
  18628. /**
  18629. * Returns the mesh position in the local space from the current World matrix values.
  18630. * Returns a new Vector3.
  18631. */
  18632. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18633. this.computeWorldMatrix();
  18634. var invLocalWorldMatrix = this._localWorld.clone();
  18635. invLocalWorldMatrix.invert();
  18636. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18637. };
  18638. /**
  18639. * Translates the mesh along the passed Vector3 in its local space.
  18640. * Returns the TransformNode.
  18641. */
  18642. TransformNode.prototype.locallyTranslate = function (vector3) {
  18643. this.computeWorldMatrix(true);
  18644. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18645. return this;
  18646. };
  18647. /**
  18648. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18649. * @param targetPoint the position (must be in same space as current mesh) to look at
  18650. * @param yawCor optional yaw (y-axis) correction in radians
  18651. * @param pitchCor optional pitch (x-axis) correction in radians
  18652. * @param rollCor optional roll (z-axis) correction in radians
  18653. * @param space the choosen space of the target
  18654. * @returns the TransformNode.
  18655. */
  18656. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18657. if (yawCor === void 0) { yawCor = 0; }
  18658. if (pitchCor === void 0) { pitchCor = 0; }
  18659. if (rollCor === void 0) { rollCor = 0; }
  18660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18661. var dv = TransformNode._lookAtVectorCache;
  18662. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18663. targetPoint.subtractToRef(pos, dv);
  18664. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18665. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18666. var pitch = Math.atan2(dv.y, len);
  18667. if (this.rotationQuaternion) {
  18668. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18669. }
  18670. else {
  18671. this.rotation.x = pitch + pitchCor;
  18672. this.rotation.y = yaw + yawCor;
  18673. this.rotation.z = rollCor;
  18674. }
  18675. return this;
  18676. };
  18677. /**
  18678. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18679. * This Vector3 is expressed in the World space.
  18680. */
  18681. TransformNode.prototype.getDirection = function (localAxis) {
  18682. var result = BABYLON.Vector3.Zero();
  18683. this.getDirectionToRef(localAxis, result);
  18684. return result;
  18685. };
  18686. /**
  18687. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18688. * localAxis is expressed in the mesh local space.
  18689. * result is computed in the Wordl space from the mesh World matrix.
  18690. * Returns the TransformNode.
  18691. */
  18692. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18693. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18694. return this;
  18695. };
  18696. /**
  18697. * Sets a new pivot point to the current node
  18698. * @param point defines the new pivot point to use
  18699. * @param space defines if the point is in world or local space (local by default)
  18700. * @returns the current TransformNode
  18701. */
  18702. TransformNode.prototype.setPivotPoint = function (point, space) {
  18703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18704. if (this.getScene().getRenderId() == 0) {
  18705. this.computeWorldMatrix(true);
  18706. }
  18707. var wm = this.getWorldMatrix();
  18708. if (space == BABYLON.Space.WORLD) {
  18709. var tmat = BABYLON.Tmp.Matrix[0];
  18710. wm.invertToRef(tmat);
  18711. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18712. }
  18713. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18714. };
  18715. /**
  18716. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18717. */
  18718. TransformNode.prototype.getPivotPoint = function () {
  18719. var point = BABYLON.Vector3.Zero();
  18720. this.getPivotPointToRef(point);
  18721. return point;
  18722. };
  18723. /**
  18724. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.getPivotPointToRef = function (result) {
  18728. result.x = -this._pivotMatrix.m[12];
  18729. result.y = -this._pivotMatrix.m[13];
  18730. result.z = -this._pivotMatrix.m[14];
  18731. return this;
  18732. };
  18733. /**
  18734. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18735. */
  18736. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18737. var point = BABYLON.Vector3.Zero();
  18738. this.getAbsolutePivotPointToRef(point);
  18739. return point;
  18740. };
  18741. /**
  18742. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18743. * Returns the TransformNode.
  18744. */
  18745. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18746. result.x = this._pivotMatrix.m[12];
  18747. result.y = this._pivotMatrix.m[13];
  18748. result.z = this._pivotMatrix.m[14];
  18749. this.getPivotPointToRef(result);
  18750. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18751. return this;
  18752. };
  18753. /**
  18754. * Defines the passed node as the parent of the current node.
  18755. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18756. * Returns the TransformNode.
  18757. */
  18758. TransformNode.prototype.setParent = function (node) {
  18759. if (!node && !this.parent) {
  18760. return this;
  18761. }
  18762. if (!node) {
  18763. var rotation = BABYLON.Tmp.Quaternion[0];
  18764. var position = BABYLON.Tmp.Vector3[0];
  18765. var scale = BABYLON.Tmp.Vector3[1];
  18766. if (this.parent && this.parent.computeWorldMatrix) {
  18767. this.parent.computeWorldMatrix(true);
  18768. }
  18769. this.computeWorldMatrix(true);
  18770. this.getWorldMatrix().decompose(scale, rotation, position);
  18771. if (this.rotationQuaternion) {
  18772. this.rotationQuaternion.copyFrom(rotation);
  18773. }
  18774. else {
  18775. rotation.toEulerAnglesToRef(this.rotation);
  18776. }
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. this.position.x = position.x;
  18781. this.position.y = position.y;
  18782. this.position.z = position.z;
  18783. }
  18784. else {
  18785. var rotation = BABYLON.Tmp.Quaternion[0];
  18786. var position = BABYLON.Tmp.Vector3[0];
  18787. var scale = BABYLON.Tmp.Vector3[1];
  18788. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18789. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18790. this.computeWorldMatrix(true);
  18791. node.computeWorldMatrix(true);
  18792. node.getWorldMatrix().invertToRef(invParentMatrix);
  18793. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18794. diffMatrix.decompose(scale, rotation, position);
  18795. if (this.rotationQuaternion) {
  18796. this.rotationQuaternion.copyFrom(rotation);
  18797. }
  18798. else {
  18799. rotation.toEulerAnglesToRef(this.rotation);
  18800. }
  18801. this.position.x = position.x;
  18802. this.position.y = position.y;
  18803. this.position.z = position.z;
  18804. this.scaling.x = scale.x;
  18805. this.scaling.y = scale.y;
  18806. this.scaling.z = scale.z;
  18807. }
  18808. this.parent = node;
  18809. return this;
  18810. };
  18811. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18812. get: function () {
  18813. return this._nonUniformScaling;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18819. if (this._nonUniformScaling === value) {
  18820. return false;
  18821. }
  18822. this._nonUniformScaling = value;
  18823. return true;
  18824. };
  18825. /**
  18826. * Attach the current TransformNode to another TransformNode associated with a bone
  18827. * @param bone Bone affecting the TransformNode
  18828. * @param affectedTransformNode TransformNode associated with the bone
  18829. */
  18830. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18831. this._transformToBoneReferal = affectedTransformNode;
  18832. this.parent = bone;
  18833. if (bone.getWorldMatrix().determinant() < 0) {
  18834. this.scalingDeterminant *= -1;
  18835. }
  18836. return this;
  18837. };
  18838. TransformNode.prototype.detachFromBone = function () {
  18839. if (!this.parent) {
  18840. return this;
  18841. }
  18842. if (this.parent.getWorldMatrix().determinant() < 0) {
  18843. this.scalingDeterminant *= -1;
  18844. }
  18845. this._transformToBoneReferal = null;
  18846. this.parent = null;
  18847. return this;
  18848. };
  18849. /**
  18850. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18851. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18852. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18853. * The passed axis is also normalized.
  18854. * Returns the TransformNode.
  18855. */
  18856. TransformNode.prototype.rotate = function (axis, amount, space) {
  18857. axis.normalize();
  18858. if (!this.rotationQuaternion) {
  18859. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18860. this.rotation = BABYLON.Vector3.Zero();
  18861. }
  18862. var rotationQuaternion;
  18863. if (!space || space === BABYLON.Space.LOCAL) {
  18864. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18865. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18866. }
  18867. else {
  18868. if (this.parent) {
  18869. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18870. invertParentWorldMatrix.invert();
  18871. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18872. }
  18873. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18874. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18880. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18881. * The passed axis is also normalized.
  18882. * Returns the TransformNode.
  18883. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18884. */
  18885. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18886. axis.normalize();
  18887. if (!this.rotationQuaternion) {
  18888. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18889. this.rotation.copyFromFloats(0, 0, 0);
  18890. }
  18891. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18892. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18893. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18894. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18895. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18896. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18897. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18898. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18899. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18900. return this;
  18901. };
  18902. /**
  18903. * Translates the mesh along the axis vector for the passed distance in the given space.
  18904. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18905. * Returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.translate = function (axis, distance, space) {
  18908. var displacementVector = axis.scale(distance);
  18909. if (!space || space === BABYLON.Space.LOCAL) {
  18910. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18911. this.setPositionWithLocalVector(tempV3);
  18912. }
  18913. else {
  18914. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18915. }
  18916. return this;
  18917. };
  18918. /**
  18919. * Adds a rotation step to the mesh current rotation.
  18920. * x, y, z are Euler angles expressed in radians.
  18921. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18922. * This means this rotation is made in the mesh local space only.
  18923. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18924. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18925. * ```javascript
  18926. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18927. * ```
  18928. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18929. * 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.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.addRotation = function (x, y, z) {
  18933. var rotationQuaternion;
  18934. if (this.rotationQuaternion) {
  18935. rotationQuaternion = this.rotationQuaternion;
  18936. }
  18937. else {
  18938. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18939. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18940. }
  18941. var accumulation = BABYLON.Tmp.Quaternion[0];
  18942. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18943. rotationQuaternion.multiplyInPlace(accumulation);
  18944. if (!this.rotationQuaternion) {
  18945. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18946. }
  18947. return this;
  18948. };
  18949. /**
  18950. * Computes the mesh World matrix and returns it.
  18951. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18952. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18953. * If the parameter `force`is set to `true`, the actual computation is done.
  18954. * Returns the mesh World Matrix.
  18955. */
  18956. TransformNode.prototype.computeWorldMatrix = function (force) {
  18957. if (this._isWorldMatrixFrozen) {
  18958. return this._worldMatrix;
  18959. }
  18960. if (!force && this.isSynchronized(true)) {
  18961. this._currentRenderId = this.getScene().getRenderId();
  18962. return this._worldMatrix;
  18963. }
  18964. this._cache.position.copyFrom(this.position);
  18965. this._cache.scaling.copyFrom(this.scaling);
  18966. this._cache.pivotMatrixUpdated = false;
  18967. this._cache.billboardMode = this.billboardMode;
  18968. this._currentRenderId = this.getScene().getRenderId();
  18969. this._childRenderId = this.getScene().getRenderId();
  18970. this._isDirty = false;
  18971. // Scaling
  18972. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18973. // Rotation
  18974. //rotate, if quaternion is set and rotation was used
  18975. if (this.rotationQuaternion) {
  18976. var len = this.rotation.length();
  18977. if (len) {
  18978. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18979. this.rotation.copyFromFloats(0, 0, 0);
  18980. }
  18981. }
  18982. if (this.rotationQuaternion) {
  18983. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18985. }
  18986. else {
  18987. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18988. this._cache.rotation.copyFrom(this.rotation);
  18989. }
  18990. // Translation
  18991. var camera = this.getScene().activeCamera;
  18992. if (this.infiniteDistance && !this.parent && camera) {
  18993. var cameraWorldMatrix = camera.getWorldMatrix();
  18994. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18995. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18996. }
  18997. else {
  18998. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18999. }
  19000. // Composing transformations
  19001. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19002. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19003. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19004. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19005. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19006. // Need to decompose each rotation here
  19007. var currentPosition = BABYLON.Tmp.Vector3[3];
  19008. if (this.parent && this.parent.getWorldMatrix) {
  19009. if (this._transformToBoneReferal) {
  19010. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19011. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19012. }
  19013. else {
  19014. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19015. }
  19016. }
  19017. else {
  19018. currentPosition.copyFrom(this.position);
  19019. }
  19020. currentPosition.subtractInPlace(camera.globalPosition);
  19021. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19022. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19023. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19024. }
  19025. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19026. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19027. }
  19028. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19029. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19030. }
  19031. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. else {
  19034. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19035. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19036. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19037. }
  19038. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19039. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Post multiply inverse of pivotMatrix
  19042. if (this._postMultiplyPivotMatrix) {
  19043. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19044. }
  19045. // Local world
  19046. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19047. // Parent
  19048. if (this.parent && this.parent.getWorldMatrix) {
  19049. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19050. if (this._transformToBoneReferal) {
  19051. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19052. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19053. }
  19054. else {
  19055. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19056. }
  19057. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19058. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19059. this._worldMatrix.copyFrom(this._localWorld);
  19060. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19061. }
  19062. else {
  19063. if (this._transformToBoneReferal) {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19065. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19066. }
  19067. else {
  19068. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19069. }
  19070. }
  19071. this._markSyncedWithParent();
  19072. }
  19073. else {
  19074. this._worldMatrix.copyFrom(this._localWorld);
  19075. }
  19076. // Normal matrix
  19077. if (!this.ignoreNonUniformScaling) {
  19078. if (this.scaling.isNonUniform) {
  19079. this._updateNonUniformScalingState(true);
  19080. }
  19081. else if (this.parent && this.parent._nonUniformScaling) {
  19082. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19083. }
  19084. else {
  19085. this._updateNonUniformScalingState(false);
  19086. }
  19087. }
  19088. else {
  19089. this._updateNonUniformScalingState(false);
  19090. }
  19091. this._afterComputeWorldMatrix();
  19092. // Absolute position
  19093. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19094. // Callbacks
  19095. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19096. if (!this._poseMatrix) {
  19097. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19098. }
  19099. // Cache the determinant
  19100. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19101. return this._worldMatrix;
  19102. };
  19103. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19104. };
  19105. /**
  19106. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19107. * @param func: callback function to add
  19108. *
  19109. * Returns the TransformNode.
  19110. */
  19111. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19112. this.onAfterWorldMatrixUpdateObservable.add(func);
  19113. return this;
  19114. };
  19115. /**
  19116. * Removes a registered callback function.
  19117. * Returns the TransformNode.
  19118. */
  19119. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19120. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19121. return this;
  19122. };
  19123. /**
  19124. * Clone the current transform node
  19125. * Returns the new transform node
  19126. * @param name Name of the new clone
  19127. * @param newParent New parent for the clone
  19128. * @param doNotCloneChildren Do not clone children hierarchy
  19129. */
  19130. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19131. var _this = this;
  19132. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19133. result.name = name;
  19134. result.id = name;
  19135. if (newParent) {
  19136. result.parent = newParent;
  19137. }
  19138. if (!doNotCloneChildren) {
  19139. // Children
  19140. var directDescendants = this.getDescendants(true);
  19141. for (var index = 0; index < directDescendants.length; index++) {
  19142. var child = directDescendants[index];
  19143. if (child.clone) {
  19144. child.clone(name + "." + child.name, result);
  19145. }
  19146. }
  19147. }
  19148. return result;
  19149. };
  19150. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19151. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19152. serializationObject.type = this.getClassName();
  19153. // Parent
  19154. if (this.parent) {
  19155. serializationObject.parentId = this.parent.id;
  19156. }
  19157. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19158. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19159. }
  19160. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19161. serializationObject.isEnabled = this.isEnabled();
  19162. // Parent
  19163. if (this.parent) {
  19164. serializationObject.parentId = this.parent.id;
  19165. }
  19166. return serializationObject;
  19167. };
  19168. // Statics
  19169. /**
  19170. * Returns a new TransformNode object parsed from the source provided.
  19171. * The parameter `parsedMesh` is the source.
  19172. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19173. */
  19174. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19175. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19176. if (BABYLON.Tags) {
  19177. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19178. }
  19179. if (parsedTransformNode.localMatrix) {
  19180. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19181. }
  19182. else if (parsedTransformNode.pivotMatrix) {
  19183. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19184. }
  19185. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19186. // Parent
  19187. if (parsedTransformNode.parentId) {
  19188. transformNode._waitingParentId = parsedTransformNode.parentId;
  19189. }
  19190. return transformNode;
  19191. };
  19192. /**
  19193. * Releases resources associated with this transform node.
  19194. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19195. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19196. */
  19197. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19198. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19199. // Animations
  19200. this.getScene().stopAnimation(this);
  19201. // Remove from scene
  19202. this.getScene().removeTransformNode(this);
  19203. this.onAfterWorldMatrixUpdateObservable.clear();
  19204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19205. };
  19206. // Statics
  19207. TransformNode.BILLBOARDMODE_NONE = 0;
  19208. TransformNode.BILLBOARDMODE_X = 1;
  19209. TransformNode.BILLBOARDMODE_Y = 2;
  19210. TransformNode.BILLBOARDMODE_Z = 4;
  19211. TransformNode.BILLBOARDMODE_ALL = 7;
  19212. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19213. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19214. __decorate([
  19215. BABYLON.serializeAsVector3()
  19216. ], TransformNode.prototype, "_rotation", void 0);
  19217. __decorate([
  19218. BABYLON.serializeAsQuaternion()
  19219. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19220. __decorate([
  19221. BABYLON.serializeAsVector3()
  19222. ], TransformNode.prototype, "_scaling", void 0);
  19223. __decorate([
  19224. BABYLON.serialize()
  19225. ], TransformNode.prototype, "billboardMode", void 0);
  19226. __decorate([
  19227. BABYLON.serialize()
  19228. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19229. __decorate([
  19230. BABYLON.serialize()
  19231. ], TransformNode.prototype, "infiniteDistance", void 0);
  19232. __decorate([
  19233. BABYLON.serialize()
  19234. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19235. __decorate([
  19236. BABYLON.serializeAsVector3()
  19237. ], TransformNode.prototype, "position", void 0);
  19238. return TransformNode;
  19239. }(BABYLON.Node));
  19240. BABYLON.TransformNode = TransformNode;
  19241. })(BABYLON || (BABYLON = {}));
  19242. //# sourceMappingURL=babylon.transformNode.js.map
  19243. var BABYLON;
  19244. (function (BABYLON) {
  19245. /**
  19246. * Class used to store all common mesh properties
  19247. */
  19248. var AbstractMesh = /** @class */ (function (_super) {
  19249. __extends(AbstractMesh, _super);
  19250. // Constructor
  19251. /**
  19252. * Creates a new AbstractMesh
  19253. * @param name defines the name of the mesh
  19254. * @param scene defines the hosting scene
  19255. */
  19256. function AbstractMesh(name, scene) {
  19257. if (scene === void 0) { scene = null; }
  19258. var _this = _super.call(this, name, scene, false) || this;
  19259. _this._facetNb = 0; // facet number
  19260. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19261. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19262. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19263. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19264. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19265. _this._subDiv = {
  19266. max: 1,
  19267. X: 1,
  19268. Y: 1,
  19269. Z: 1
  19270. };
  19271. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19272. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19273. // Events
  19274. /**
  19275. * An event triggered when this mesh collides with another one
  19276. */
  19277. _this.onCollideObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when the collision's position changes
  19280. */
  19281. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when material is changed
  19284. */
  19285. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19286. // Properties
  19287. /**
  19288. * Gets or sets the orientation for POV movement & rotation
  19289. */
  19290. _this.definedFacingForward = true;
  19291. /**
  19292. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19293. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19294. * * 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.
  19295. * @see http://doc.babylonjs.com/features/occlusionquery
  19296. */
  19297. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19298. /**
  19299. * 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:
  19300. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19301. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19302. * * 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.
  19303. * @see http://doc.babylonjs.com/features/occlusionquery
  19304. */
  19305. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19306. /**
  19307. * 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.
  19308. * The default value is -1 which means don't break the query and wait till the result
  19309. * @see http://doc.babylonjs.com/features/occlusionquery
  19310. */
  19311. _this.occlusionRetryCount = -1;
  19312. /** @hidden */
  19313. _this._occlusionInternalRetryCounter = 0;
  19314. /** @hidden */
  19315. _this._isOccluded = false;
  19316. /** @hidden */
  19317. _this._isOcclusionQueryInProgress = false;
  19318. _this._visibility = 1.0;
  19319. /** Gets or sets the alpha index used to sort transparent meshes
  19320. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19321. */
  19322. _this.alphaIndex = Number.MAX_VALUE;
  19323. /**
  19324. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19325. */
  19326. _this.isVisible = true;
  19327. /**
  19328. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19329. */
  19330. _this.isPickable = true;
  19331. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19332. _this.showSubMeshesBoundingBox = false;
  19333. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19334. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19335. */
  19336. _this.isBlocker = false;
  19337. /**
  19338. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19339. */
  19340. _this.enablePointerMoveEvents = false;
  19341. /**
  19342. * Specifies the rendering group id for this mesh (0 by default)
  19343. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19344. */
  19345. _this.renderingGroupId = 0;
  19346. _this._receiveShadows = false;
  19347. /**
  19348. * Gets or sets a boolean indicating if the outline must be rendered as well
  19349. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19350. */
  19351. _this.renderOutline = false;
  19352. /** Defines color to use when rendering outline */
  19353. _this.outlineColor = BABYLON.Color3.Red();
  19354. /** Define width to use when rendering outline */
  19355. _this.outlineWidth = 0.02;
  19356. /**
  19357. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19358. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19359. */
  19360. _this.renderOverlay = false;
  19361. /** Defines color to use when rendering overlay */
  19362. _this.overlayColor = BABYLON.Color3.Red();
  19363. /** Defines alpha to use when rendering overlay */
  19364. _this.overlayAlpha = 0.5;
  19365. _this._hasVertexAlpha = false;
  19366. _this._useVertexColors = true;
  19367. _this._computeBonesUsingShaders = true;
  19368. _this._numBoneInfluencers = 4;
  19369. _this._applyFog = true;
  19370. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19371. _this.useOctreeForRenderingSelection = true;
  19372. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19373. _this.useOctreeForPicking = true;
  19374. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19375. _this.useOctreeForCollisions = true;
  19376. _this._layerMask = 0x0FFFFFFF;
  19377. /**
  19378. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19379. */
  19380. _this.alwaysSelectAsActiveMesh = false;
  19381. /**
  19382. * Gets or sets the current action manager
  19383. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19384. */
  19385. _this.actionManager = null;
  19386. /**
  19387. * Gets or sets impostor used for physic simulation
  19388. * @see http://doc.babylonjs.com/features/physics_engine
  19389. */
  19390. _this.physicsImpostor = null;
  19391. // Collisions
  19392. _this._checkCollisions = false;
  19393. _this._collisionMask = -1;
  19394. _this._collisionGroup = -1;
  19395. /**
  19396. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19397. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19398. */
  19399. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19400. /**
  19401. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19402. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19403. */
  19404. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19405. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19406. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19407. // Edges
  19408. /**
  19409. * Defines edge width used when edgesRenderer is enabled
  19410. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19411. */
  19412. _this.edgesWidth = 1;
  19413. /**
  19414. * Defines edge color used when edgesRenderer is enabled
  19415. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19416. */
  19417. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19418. // Cache
  19419. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19420. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19421. /** @hidden */
  19422. _this._renderId = 0;
  19423. /** @hidden */
  19424. _this._intersectionsInProgress = new Array();
  19425. /** @hidden */
  19426. _this._unIndexed = false;
  19427. /** @hidden */
  19428. _this._lightSources = new Array();
  19429. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19430. if (collidedMesh === void 0) { collidedMesh = null; }
  19431. //TODO move this to the collision coordinator!
  19432. if (_this.getScene().workerCollisions)
  19433. newPosition.multiplyInPlace(_this._collider._radius);
  19434. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19435. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19436. _this.position.addInPlace(_this._diffPositionForCollisions);
  19437. }
  19438. if (collidedMesh) {
  19439. _this.onCollideObservable.notifyObservers(collidedMesh);
  19440. }
  19441. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19442. };
  19443. _this.getScene().addMesh(_this);
  19444. _this._resyncLightSources();
  19445. return _this;
  19446. }
  19447. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19448. /**
  19449. * No billboard
  19450. */
  19451. get: function () {
  19452. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19458. /** Billboard on X axis */
  19459. get: function () {
  19460. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19466. /** Billboard on Y axis */
  19467. get: function () {
  19468. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19469. },
  19470. enumerable: true,
  19471. configurable: true
  19472. });
  19473. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19474. /** Billboard on Z axis */
  19475. get: function () {
  19476. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19482. /** Billboard on all axes */
  19483. get: function () {
  19484. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19490. /**
  19491. * Gets the number of facets in the mesh
  19492. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19493. */
  19494. get: function () {
  19495. return this._facetNb;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19501. /**
  19502. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19503. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19504. */
  19505. get: function () {
  19506. return this._partitioningSubdivisions;
  19507. },
  19508. set: function (nb) {
  19509. this._partitioningSubdivisions = nb;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19515. /**
  19516. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19517. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19518. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19519. */
  19520. get: function () {
  19521. return this._partitioningBBoxRatio;
  19522. },
  19523. set: function (ratio) {
  19524. this._partitioningBBoxRatio = ratio;
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19530. /**
  19531. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19532. * Works only for updatable meshes.
  19533. * Doesn't work with multi-materials
  19534. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19535. */
  19536. get: function () {
  19537. return this._facetDepthSort;
  19538. },
  19539. set: function (sort) {
  19540. this._facetDepthSort = sort;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19546. /**
  19547. * The location (Vector3) where the facet depth sort must be computed from.
  19548. * By default, the active camera position.
  19549. * Used only when facet depth sort is enabled
  19550. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19551. */
  19552. get: function () {
  19553. return this._facetDepthSortFrom;
  19554. },
  19555. set: function (location) {
  19556. this._facetDepthSortFrom = location;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19562. /**
  19563. * gets a boolean indicating if facetData is enabled
  19564. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19565. */
  19566. get: function () {
  19567. return this._facetDataEnabled;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. /** @hidden */
  19573. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19574. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19575. return false;
  19576. }
  19577. this._markSubMeshesAsMiscDirty();
  19578. return true;
  19579. };
  19580. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19581. /** Set a function to call when this mesh collides with another one */
  19582. set: function (callback) {
  19583. if (this._onCollideObserver) {
  19584. this.onCollideObservable.remove(this._onCollideObserver);
  19585. }
  19586. this._onCollideObserver = this.onCollideObservable.add(callback);
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19592. /** Set a function to call when the collision's position changes */
  19593. set: function (callback) {
  19594. if (this._onCollisionPositionChangeObserver) {
  19595. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19596. }
  19597. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19603. /**
  19604. * 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
  19605. * @see http://doc.babylonjs.com/features/occlusionquery
  19606. */
  19607. get: function () {
  19608. return this._isOccluded;
  19609. },
  19610. set: function (value) {
  19611. this._isOccluded = value;
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19617. /**
  19618. * Flag to check the progress status of the query
  19619. * @see http://doc.babylonjs.com/features/occlusionquery
  19620. */
  19621. get: function () {
  19622. return this._isOcclusionQueryInProgress;
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19628. /**
  19629. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19630. */
  19631. get: function () {
  19632. return this._visibility;
  19633. },
  19634. /**
  19635. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19636. */
  19637. set: function (value) {
  19638. if (this._visibility === value) {
  19639. return;
  19640. }
  19641. this._visibility = value;
  19642. this._markSubMeshesAsMiscDirty();
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(AbstractMesh.prototype, "material", {
  19648. /** Gets or sets current material */
  19649. get: function () {
  19650. return this._material;
  19651. },
  19652. set: function (value) {
  19653. if (this._material === value) {
  19654. return;
  19655. }
  19656. this._material = value;
  19657. if (this.onMaterialChangedObservable.hasObservers) {
  19658. this.onMaterialChangedObservable.notifyObservers(this);
  19659. }
  19660. if (!this.subMeshes) {
  19661. return;
  19662. }
  19663. this._unBindEffect();
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19669. /**
  19670. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19671. * @see http://doc.babylonjs.com/babylon101/shadows
  19672. */
  19673. get: function () {
  19674. return this._receiveShadows;
  19675. },
  19676. set: function (value) {
  19677. if (this._receiveShadows === value) {
  19678. return;
  19679. }
  19680. this._receiveShadows = value;
  19681. this._markSubMeshesAsLightDirty();
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19687. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19688. get: function () {
  19689. return this._hasVertexAlpha;
  19690. },
  19691. set: function (value) {
  19692. if (this._hasVertexAlpha === value) {
  19693. return;
  19694. }
  19695. this._hasVertexAlpha = value;
  19696. this._markSubMeshesAsAttributesDirty();
  19697. this._markSubMeshesAsMiscDirty();
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19703. /** 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) */
  19704. get: function () {
  19705. return this._useVertexColors;
  19706. },
  19707. set: function (value) {
  19708. if (this._useVertexColors === value) {
  19709. return;
  19710. }
  19711. this._useVertexColors = value;
  19712. this._markSubMeshesAsAttributesDirty();
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19718. /**
  19719. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19720. */
  19721. get: function () {
  19722. return this._computeBonesUsingShaders;
  19723. },
  19724. set: function (value) {
  19725. if (this._computeBonesUsingShaders === value) {
  19726. return;
  19727. }
  19728. this._computeBonesUsingShaders = value;
  19729. this._markSubMeshesAsAttributesDirty();
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19735. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19736. get: function () {
  19737. return this._numBoneInfluencers;
  19738. },
  19739. set: function (value) {
  19740. if (this._numBoneInfluencers === value) {
  19741. return;
  19742. }
  19743. this._numBoneInfluencers = value;
  19744. this._markSubMeshesAsAttributesDirty();
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19750. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19751. get: function () {
  19752. return this._applyFog;
  19753. },
  19754. set: function (value) {
  19755. if (this._applyFog === value) {
  19756. return;
  19757. }
  19758. this._applyFog = value;
  19759. this._markSubMeshesAsMiscDirty();
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19765. /**
  19766. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19767. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19768. */
  19769. get: function () {
  19770. return this._layerMask;
  19771. },
  19772. set: function (value) {
  19773. if (value === this._layerMask) {
  19774. return;
  19775. }
  19776. this._layerMask = value;
  19777. this._resyncLightSources();
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19783. /**
  19784. * Gets or sets a collision mask used to mask collisions (default is -1).
  19785. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19786. */
  19787. get: function () {
  19788. return this._collisionMask;
  19789. },
  19790. set: function (mask) {
  19791. this._collisionMask = !isNaN(mask) ? mask : -1;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19797. /**
  19798. * Gets or sets the current collision group mask (-1 by default).
  19799. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19800. */
  19801. get: function () {
  19802. return this._collisionGroup;
  19803. },
  19804. set: function (mask) {
  19805. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19811. /** @hidden */
  19812. get: function () {
  19813. return null;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19819. get: function () {
  19820. return this._skeleton;
  19821. },
  19822. /**
  19823. * Gets or sets a skeleton to apply skining transformations
  19824. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19825. */
  19826. set: function (value) {
  19827. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19828. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19829. }
  19830. if (value && value.needInitialSkinMatrix) {
  19831. value._registerMeshWithPoseMatrix(this);
  19832. }
  19833. this._skeleton = value;
  19834. if (!this._skeleton) {
  19835. this._bonesTransformMatrices = null;
  19836. }
  19837. this._markSubMeshesAsAttributesDirty();
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. /**
  19843. * Returns the string "AbstractMesh"
  19844. * @returns "AbstractMesh"
  19845. */
  19846. AbstractMesh.prototype.getClassName = function () {
  19847. return "AbstractMesh";
  19848. };
  19849. /**
  19850. * Gets a string representation of the current mesh
  19851. * @param fullDetails defines a boolean indicating if full details must be included
  19852. * @returns a string representation of the current mesh
  19853. */
  19854. AbstractMesh.prototype.toString = function (fullDetails) {
  19855. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19856. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19857. if (this._skeleton) {
  19858. ret += ", skeleton: " + this._skeleton.name;
  19859. }
  19860. if (fullDetails) {
  19861. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19862. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19863. }
  19864. return ret;
  19865. };
  19866. /** @hidden */
  19867. AbstractMesh.prototype._rebuild = function () {
  19868. if (this._occlusionQuery) {
  19869. this._occlusionQuery = null;
  19870. }
  19871. if (this._edgesRenderer) {
  19872. this._edgesRenderer._rebuild();
  19873. }
  19874. if (!this.subMeshes) {
  19875. return;
  19876. }
  19877. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19878. var subMesh = _a[_i];
  19879. subMesh._rebuild();
  19880. }
  19881. };
  19882. /** @hidden */
  19883. AbstractMesh.prototype._resyncLightSources = function () {
  19884. this._lightSources.length = 0;
  19885. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19886. var light = _a[_i];
  19887. if (!light.isEnabled()) {
  19888. continue;
  19889. }
  19890. if (light.canAffectMesh(this)) {
  19891. this._lightSources.push(light);
  19892. }
  19893. }
  19894. this._markSubMeshesAsLightDirty();
  19895. };
  19896. /** @hidden */
  19897. AbstractMesh.prototype._resyncLighSource = function (light) {
  19898. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19899. var index = this._lightSources.indexOf(light);
  19900. if (index === -1) {
  19901. if (!isIn) {
  19902. return;
  19903. }
  19904. this._lightSources.push(light);
  19905. }
  19906. else {
  19907. if (isIn) {
  19908. return;
  19909. }
  19910. this._lightSources.splice(index, 1);
  19911. }
  19912. this._markSubMeshesAsLightDirty();
  19913. };
  19914. /** @hidden */
  19915. AbstractMesh.prototype._unBindEffect = function () {
  19916. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19917. var subMesh = _a[_i];
  19918. subMesh.setEffect(null);
  19919. }
  19920. };
  19921. /** @hidden */
  19922. AbstractMesh.prototype._removeLightSource = function (light) {
  19923. var index = this._lightSources.indexOf(light);
  19924. if (index === -1) {
  19925. return;
  19926. }
  19927. this._lightSources.splice(index, 1);
  19928. this._markSubMeshesAsLightDirty();
  19929. };
  19930. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19931. if (!this.subMeshes) {
  19932. return;
  19933. }
  19934. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19935. var subMesh = _a[_i];
  19936. if (subMesh._materialDefines) {
  19937. func(subMesh._materialDefines);
  19938. }
  19939. }
  19940. };
  19941. /** @hidden */
  19942. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19943. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19944. };
  19945. /** @hidden */
  19946. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19947. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19948. };
  19949. /** @hidden */
  19950. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19951. if (!this.subMeshes) {
  19952. return;
  19953. }
  19954. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19955. var subMesh = _a[_i];
  19956. var material = subMesh.getMaterial();
  19957. if (material) {
  19958. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19959. }
  19960. }
  19961. };
  19962. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19963. /**
  19964. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19965. */
  19966. get: function () {
  19967. return this._scaling;
  19968. },
  19969. set: function (newScaling) {
  19970. this._scaling = newScaling;
  19971. if (this.physicsImpostor) {
  19972. this.physicsImpostor.forceUpdate();
  19973. }
  19974. },
  19975. enumerable: true,
  19976. configurable: true
  19977. });
  19978. // Methods
  19979. /**
  19980. * Disables the mesh edge rendering mode
  19981. * @returns the currentAbstractMesh
  19982. */
  19983. AbstractMesh.prototype.disableEdgesRendering = function () {
  19984. if (this._edgesRenderer) {
  19985. this._edgesRenderer.dispose();
  19986. this._edgesRenderer = null;
  19987. }
  19988. return this;
  19989. };
  19990. /**
  19991. * Enables the edge rendering mode on the mesh.
  19992. * This mode makes the mesh edges visible
  19993. * @param epsilon defines the maximal distance between two angles to detect a face
  19994. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19995. * @returns the currentAbstractMesh
  19996. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19997. */
  19998. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19999. if (epsilon === void 0) { epsilon = 0.95; }
  20000. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20001. this.disableEdgesRendering();
  20002. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20003. return this;
  20004. };
  20005. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20006. /**
  20007. * Gets the edgesRenderer associated with the mesh
  20008. */
  20009. get: function () {
  20010. return this._edgesRenderer;
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20016. /**
  20017. * Returns true if the mesh is blocked. Implemented by child classes
  20018. */
  20019. get: function () {
  20020. return false;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. /**
  20026. * Returns the mesh itself by default. Implemented by child classes
  20027. * @param camera defines the camera to use to pick the right LOD level
  20028. * @returns the currentAbstractMesh
  20029. */
  20030. AbstractMesh.prototype.getLOD = function (camera) {
  20031. return this;
  20032. };
  20033. /**
  20034. * Returns 0 by default. Implemented by child classes
  20035. * @returns an integer
  20036. */
  20037. AbstractMesh.prototype.getTotalVertices = function () {
  20038. return 0;
  20039. };
  20040. /**
  20041. * Returns null by default. Implemented by child classes
  20042. * @returns null
  20043. */
  20044. AbstractMesh.prototype.getIndices = function () {
  20045. return null;
  20046. };
  20047. /**
  20048. * Returns the array of the requested vertex data kind. Implemented by child classes
  20049. * @param kind defines the vertex data kind to use
  20050. * @returns null
  20051. */
  20052. AbstractMesh.prototype.getVerticesData = function (kind) {
  20053. return null;
  20054. };
  20055. /**
  20056. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20057. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20058. * Note that a new underlying VertexBuffer object is created each call.
  20059. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20060. * @param kind defines vertex data kind:
  20061. * * BABYLON.VertexBuffer.PositionKind
  20062. * * BABYLON.VertexBuffer.UVKind
  20063. * * BABYLON.VertexBuffer.UV2Kind
  20064. * * BABYLON.VertexBuffer.UV3Kind
  20065. * * BABYLON.VertexBuffer.UV4Kind
  20066. * * BABYLON.VertexBuffer.UV5Kind
  20067. * * BABYLON.VertexBuffer.UV6Kind
  20068. * * BABYLON.VertexBuffer.ColorKind
  20069. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20070. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20071. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20072. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20073. * @param data defines the data source
  20074. * @param updatable defines if the data must be flagged as updatable (or static)
  20075. * @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
  20076. * @returns the current mesh
  20077. */
  20078. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20079. return this;
  20080. };
  20081. /**
  20082. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20083. * If the mesh has no geometry, it is simply returned as it is.
  20084. * @param kind defines vertex data kind:
  20085. * * BABYLON.VertexBuffer.PositionKind
  20086. * * BABYLON.VertexBuffer.UVKind
  20087. * * BABYLON.VertexBuffer.UV2Kind
  20088. * * BABYLON.VertexBuffer.UV3Kind
  20089. * * BABYLON.VertexBuffer.UV4Kind
  20090. * * BABYLON.VertexBuffer.UV5Kind
  20091. * * BABYLON.VertexBuffer.UV6Kind
  20092. * * BABYLON.VertexBuffer.ColorKind
  20093. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20094. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20095. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20096. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20097. * @param data defines the data source
  20098. * @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
  20099. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20100. * @returns the current mesh
  20101. */
  20102. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20103. return this;
  20104. };
  20105. /**
  20106. * Sets the mesh indices,
  20107. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20108. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20109. * @param totalVertices Defines the total number of vertices
  20110. * @returns the current mesh
  20111. */
  20112. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20113. return this;
  20114. };
  20115. /**
  20116. * Gets a boolean indicating if specific vertex data is present
  20117. * @param kind defines the vertex data kind to use
  20118. * @returns true is data kind is present
  20119. */
  20120. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20121. return false;
  20122. };
  20123. /**
  20124. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20125. * @returns a BoundingInfo
  20126. */
  20127. AbstractMesh.prototype.getBoundingInfo = function () {
  20128. if (this._masterMesh) {
  20129. return this._masterMesh.getBoundingInfo();
  20130. }
  20131. if (!this._boundingInfo) {
  20132. // this._boundingInfo is being created here
  20133. this._updateBoundingInfo();
  20134. }
  20135. // cannot be null.
  20136. return this._boundingInfo;
  20137. };
  20138. /**
  20139. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20140. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20144. if (includeDescendants === void 0) { includeDescendants = true; }
  20145. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20146. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20147. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20148. if (maxDimension === 0) {
  20149. return this;
  20150. }
  20151. var scale = 1 / maxDimension;
  20152. this.scaling.scaleInPlace(scale);
  20153. return this;
  20154. };
  20155. /**
  20156. * Overwrite the current bounding info
  20157. * @param boundingInfo defines the new bounding info
  20158. * @returns the current mesh
  20159. */
  20160. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20161. this._boundingInfo = boundingInfo;
  20162. return this;
  20163. };
  20164. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20165. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20166. get: function () {
  20167. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. /** @hidden */
  20173. AbstractMesh.prototype._preActivate = function () {
  20174. };
  20175. /** @hidden */
  20176. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20177. };
  20178. /** @hidden */
  20179. AbstractMesh.prototype._activate = function (renderId) {
  20180. this._renderId = renderId;
  20181. };
  20182. /**
  20183. * Gets the current world matrix
  20184. * @returns a Matrix
  20185. */
  20186. AbstractMesh.prototype.getWorldMatrix = function () {
  20187. if (this._masterMesh) {
  20188. return this._masterMesh.getWorldMatrix();
  20189. }
  20190. return _super.prototype.getWorldMatrix.call(this);
  20191. };
  20192. /** @hidden */
  20193. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20194. if (this._masterMesh) {
  20195. return this._masterMesh._getWorldMatrixDeterminant();
  20196. }
  20197. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20198. };
  20199. // ================================== Point of View Movement =================================
  20200. /**
  20201. * Perform relative position change from the point of view of behind the front of the mesh.
  20202. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20203. * Supports definition of mesh facing forward or backward
  20204. * @param amountRight defines the distance on the right axis
  20205. * @param amountUp defines the distance on the up axis
  20206. * @param amountForward defines the distance on the forward axis
  20207. * @returns the current mesh
  20208. */
  20209. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20210. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20211. return this;
  20212. };
  20213. /**
  20214. * Calculate relative position change from the point of view of behind the front of the mesh.
  20215. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20216. * Supports definition of mesh facing forward or backward
  20217. * @param amountRight defines the distance on the right axis
  20218. * @param amountUp defines the distance on the up axis
  20219. * @param amountForward defines the distance on the forward axis
  20220. * @returns the new displacement vector
  20221. */
  20222. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20223. var rotMatrix = new BABYLON.Matrix();
  20224. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20225. rotQuaternion.toRotationMatrix(rotMatrix);
  20226. var translationDelta = BABYLON.Vector3.Zero();
  20227. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20229. return translationDelta;
  20230. };
  20231. // ================================== Point of View Rotation =================================
  20232. /**
  20233. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20234. * Supports definition of mesh facing forward or backward
  20235. * @param flipBack defines the flip
  20236. * @param twirlClockwise defines the twirl
  20237. * @param tiltRight defines the tilt
  20238. * @returns the current mesh
  20239. */
  20240. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20241. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20242. return this;
  20243. };
  20244. /**
  20245. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20246. * Supports definition of mesh facing forward or backward.
  20247. * @param flipBack defines the flip
  20248. * @param twirlClockwise defines the twirl
  20249. * @param tiltRight defines the tilt
  20250. * @returns the new rotation vector
  20251. */
  20252. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20253. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20254. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20255. };
  20256. /**
  20257. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20258. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20259. * @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
  20260. * @returns the new bounding vectors
  20261. */
  20262. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20263. if (includeDescendants === void 0) { includeDescendants = true; }
  20264. if (predicate === void 0) { predicate = null; }
  20265. // Ensures that all world matrix will be recomputed.
  20266. this.getScene().incrementRenderId();
  20267. this.computeWorldMatrix(true);
  20268. var min;
  20269. var max;
  20270. var boundingInfo = this.getBoundingInfo();
  20271. if (!this.subMeshes) {
  20272. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20273. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20274. }
  20275. else {
  20276. min = boundingInfo.boundingBox.minimumWorld;
  20277. max = boundingInfo.boundingBox.maximumWorld;
  20278. }
  20279. if (includeDescendants) {
  20280. var descendants = this.getDescendants(false);
  20281. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20282. var descendant = descendants_1[_i];
  20283. var childMesh = descendant;
  20284. childMesh.computeWorldMatrix(true);
  20285. // Filters meshes based on custom predicate function.
  20286. if (predicate && !predicate(childMesh)) {
  20287. continue;
  20288. }
  20289. //make sure we have the needed params to get mix and max
  20290. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20291. continue;
  20292. }
  20293. var childBoundingInfo = childMesh.getBoundingInfo();
  20294. var boundingBox = childBoundingInfo.boundingBox;
  20295. var minBox = boundingBox.minimumWorld;
  20296. var maxBox = boundingBox.maximumWorld;
  20297. BABYLON.Tools.CheckExtends(minBox, min, max);
  20298. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20299. }
  20300. }
  20301. return {
  20302. min: min,
  20303. max: max
  20304. };
  20305. };
  20306. /** @hidden */
  20307. AbstractMesh.prototype._updateBoundingInfo = function () {
  20308. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20309. this._boundingInfo.update(this.worldMatrixFromCache);
  20310. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20311. return this;
  20312. };
  20313. /** @hidden */
  20314. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20315. if (!this.subMeshes) {
  20316. return this;
  20317. }
  20318. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20319. var subMesh = this.subMeshes[subIndex];
  20320. if (!subMesh.IsGlobal) {
  20321. subMesh.updateBoundingInfo(matrix);
  20322. }
  20323. }
  20324. return this;
  20325. };
  20326. /** @hidden */
  20327. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20328. // Bounding info
  20329. this._updateBoundingInfo();
  20330. };
  20331. /**
  20332. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20333. * A mesh is in the frustum if its bounding box intersects the frustum
  20334. * @param frustumPlanes defines the frustum to test
  20335. * @returns true if the mesh is in the frustum planes
  20336. */
  20337. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20338. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20339. };
  20340. /**
  20341. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20342. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20343. * @param frustumPlanes defines the frustum to test
  20344. * @returns true if the mesh is completely in the frustum planes
  20345. */
  20346. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20347. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20348. };
  20349. /**
  20350. * True if the mesh intersects another mesh or a SolidParticle object
  20351. * @param mesh defines a target mesh or SolidParticle to test
  20352. * @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)
  20353. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20354. * @returns true if there is an intersection
  20355. */
  20356. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20357. if (precise === void 0) { precise = false; }
  20358. if (!this._boundingInfo || !mesh._boundingInfo) {
  20359. return false;
  20360. }
  20361. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20362. return true;
  20363. }
  20364. if (includeDescendants) {
  20365. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20366. var child = _a[_i];
  20367. if (child.intersectsMesh(mesh, precise, true)) {
  20368. return true;
  20369. }
  20370. }
  20371. }
  20372. return false;
  20373. };
  20374. /**
  20375. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20376. * @param point defines the point to test
  20377. * @returns true if there is an intersection
  20378. */
  20379. AbstractMesh.prototype.intersectsPoint = function (point) {
  20380. if (!this._boundingInfo) {
  20381. return false;
  20382. }
  20383. return this._boundingInfo.intersectsPoint(point);
  20384. };
  20385. /**
  20386. * Gets the current physics impostor
  20387. * @see http://doc.babylonjs.com/features/physics_engine
  20388. * @returns a physics impostor or null
  20389. */
  20390. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20391. return this.physicsImpostor;
  20392. };
  20393. /**
  20394. * Gets the position of the current mesh in camera space
  20395. * @param camera defines the camera to use
  20396. * @returns a position
  20397. */
  20398. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20399. if (camera === void 0) { camera = null; }
  20400. if (!camera) {
  20401. camera = this.getScene().activeCamera;
  20402. }
  20403. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20404. };
  20405. /**
  20406. * Returns the distance from the mesh to the active camera
  20407. * @param camera defines the camera to use
  20408. * @returns the distance
  20409. */
  20410. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20411. if (camera === void 0) { camera = null; }
  20412. if (!camera) {
  20413. camera = this.getScene().activeCamera;
  20414. }
  20415. return this.absolutePosition.subtract(camera.position).length();
  20416. };
  20417. /**
  20418. * Apply a physic impulse to the mesh
  20419. * @param force defines the force to apply
  20420. * @param contactPoint defines where to apply the force
  20421. * @returns the current mesh
  20422. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20423. */
  20424. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20425. if (!this.physicsImpostor) {
  20426. return this;
  20427. }
  20428. this.physicsImpostor.applyImpulse(force, contactPoint);
  20429. return this;
  20430. };
  20431. /**
  20432. * Creates a physic joint between two meshes
  20433. * @param otherMesh defines the other mesh to use
  20434. * @param pivot1 defines the pivot to use on this mesh
  20435. * @param pivot2 defines the pivot to use on the other mesh
  20436. * @param options defines additional options (can be plugin dependent)
  20437. * @returns the current mesh
  20438. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20439. */
  20440. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20441. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20442. return this;
  20443. }
  20444. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20445. mainPivot: pivot1,
  20446. connectedPivot: pivot2,
  20447. nativeParams: options
  20448. });
  20449. return this;
  20450. };
  20451. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20452. // Collisions
  20453. /**
  20454. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20455. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20456. */
  20457. get: function () {
  20458. return this._checkCollisions;
  20459. },
  20460. set: function (collisionEnabled) {
  20461. this._checkCollisions = collisionEnabled;
  20462. if (this.getScene().workerCollisions) {
  20463. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20464. }
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20470. /**
  20471. * Gets Collider object used to compute collisions (not physics)
  20472. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20473. */
  20474. get: function () {
  20475. return this._collider;
  20476. },
  20477. enumerable: true,
  20478. configurable: true
  20479. });
  20480. /**
  20481. * Move the mesh using collision engine
  20482. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20483. * @param displacement defines the requested displacement vector
  20484. * @returns the current mesh
  20485. */
  20486. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20487. var globalPosition = this.getAbsolutePosition();
  20488. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20489. if (!this._collider) {
  20490. this._collider = new BABYLON.Collider();
  20491. }
  20492. this._collider._radius = this.ellipsoid;
  20493. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20494. return this;
  20495. };
  20496. // Submeshes octree
  20497. /**
  20498. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20499. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20500. * @param maxCapacity defines the maximum size of each block (64 by default)
  20501. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20502. * @returns the new octree
  20503. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20504. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20505. */
  20506. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20507. if (maxCapacity === void 0) { maxCapacity = 64; }
  20508. if (maxDepth === void 0) { maxDepth = 2; }
  20509. if (!this._submeshesOctree) {
  20510. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20511. }
  20512. this.computeWorldMatrix(true);
  20513. var boundingInfo = this.getBoundingInfo();
  20514. // Update octree
  20515. var bbox = boundingInfo.boundingBox;
  20516. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20517. return this._submeshesOctree;
  20518. };
  20519. // Collisions
  20520. /** @hidden */
  20521. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20522. this._generatePointsArray();
  20523. if (!this._positions) {
  20524. return this;
  20525. }
  20526. // Transformation
  20527. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20528. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20529. subMesh._lastColliderWorldVertices = [];
  20530. subMesh._trianglePlanes = [];
  20531. var start = subMesh.verticesStart;
  20532. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20533. for (var i = start; i < end; i++) {
  20534. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20535. }
  20536. }
  20537. // Collide
  20538. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20539. if (collider.collisionFound) {
  20540. collider.collidedMesh = this;
  20541. }
  20542. return this;
  20543. };
  20544. /** @hidden */
  20545. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20546. var subMeshes;
  20547. var len;
  20548. // Octrees
  20549. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20550. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20551. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20552. len = intersections.length;
  20553. subMeshes = intersections.data;
  20554. }
  20555. else {
  20556. subMeshes = this.subMeshes;
  20557. len = subMeshes.length;
  20558. }
  20559. for (var index = 0; index < len; index++) {
  20560. var subMesh = subMeshes[index];
  20561. // Bounding test
  20562. if (len > 1 && !subMesh._checkCollision(collider))
  20563. continue;
  20564. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20565. }
  20566. return this;
  20567. };
  20568. /** @hidden */
  20569. AbstractMesh.prototype._checkCollision = function (collider) {
  20570. // Bounding box test
  20571. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20572. return this;
  20573. // Transformation matrix
  20574. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20575. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20576. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20577. return this;
  20578. };
  20579. // Picking
  20580. /** @hidden */
  20581. AbstractMesh.prototype._generatePointsArray = function () {
  20582. return false;
  20583. };
  20584. /**
  20585. * Checks if the passed Ray intersects with the mesh
  20586. * @param ray defines the ray to use
  20587. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20588. * @returns the picking info
  20589. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20590. */
  20591. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20592. var pickingInfo = new BABYLON.PickingInfo();
  20593. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20594. return pickingInfo;
  20595. }
  20596. if (!this._generatePointsArray()) {
  20597. return pickingInfo;
  20598. }
  20599. var intersectInfo = null;
  20600. // Octrees
  20601. var subMeshes;
  20602. var len;
  20603. if (this._submeshesOctree && this.useOctreeForPicking) {
  20604. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20605. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20606. len = intersections.length;
  20607. subMeshes = intersections.data;
  20608. }
  20609. else {
  20610. subMeshes = this.subMeshes;
  20611. len = subMeshes.length;
  20612. }
  20613. for (var index = 0; index < len; index++) {
  20614. var subMesh = subMeshes[index];
  20615. // Bounding test
  20616. if (len > 1 && !subMesh.canIntersects(ray))
  20617. continue;
  20618. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20619. if (currentIntersectInfo) {
  20620. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20621. intersectInfo = currentIntersectInfo;
  20622. intersectInfo.subMeshId = index;
  20623. if (fastCheck) {
  20624. break;
  20625. }
  20626. }
  20627. }
  20628. }
  20629. if (intersectInfo) {
  20630. // Get picked point
  20631. var world = this.getWorldMatrix();
  20632. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20633. var direction = ray.direction.clone();
  20634. direction = direction.scale(intersectInfo.distance);
  20635. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20636. var pickedPoint = worldOrigin.add(worldDirection);
  20637. // Return result
  20638. pickingInfo.hit = true;
  20639. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20640. pickingInfo.pickedPoint = pickedPoint;
  20641. pickingInfo.pickedMesh = this;
  20642. pickingInfo.bu = intersectInfo.bu || 0;
  20643. pickingInfo.bv = intersectInfo.bv || 0;
  20644. pickingInfo.faceId = intersectInfo.faceId;
  20645. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20646. return pickingInfo;
  20647. }
  20648. return pickingInfo;
  20649. };
  20650. /**
  20651. * Clones the current mesh
  20652. * @param name defines the mesh name
  20653. * @param newParent defines the new mesh parent
  20654. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20655. * @returns the new mesh
  20656. */
  20657. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20658. return null;
  20659. };
  20660. /**
  20661. * Disposes all the submeshes of the current meshnp
  20662. * @returns the current mesh
  20663. */
  20664. AbstractMesh.prototype.releaseSubMeshes = function () {
  20665. if (this.subMeshes) {
  20666. while (this.subMeshes.length) {
  20667. this.subMeshes[0].dispose();
  20668. }
  20669. }
  20670. else {
  20671. this.subMeshes = new Array();
  20672. }
  20673. return this;
  20674. };
  20675. /**
  20676. * Releases resources associated with this abstract mesh.
  20677. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20678. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20679. */
  20680. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20681. var _this = this;
  20682. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20683. var index;
  20684. // Smart Array Retainers.
  20685. this.getScene().freeActiveMeshes();
  20686. this.getScene().freeRenderingGroups();
  20687. // Action manager
  20688. if (this.actionManager !== undefined && this.actionManager !== null) {
  20689. this.actionManager.dispose();
  20690. this.actionManager = null;
  20691. }
  20692. // Skeleton
  20693. this._skeleton = null;
  20694. // Physics
  20695. if (this.physicsImpostor) {
  20696. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20697. }
  20698. // Intersections in progress
  20699. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20700. var other = this._intersectionsInProgress[index];
  20701. var pos = other._intersectionsInProgress.indexOf(this);
  20702. other._intersectionsInProgress.splice(pos, 1);
  20703. }
  20704. this._intersectionsInProgress = [];
  20705. // Lights
  20706. var lights = this.getScene().lights;
  20707. lights.forEach(function (light) {
  20708. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20709. if (meshIndex !== -1) {
  20710. light.includedOnlyMeshes.splice(meshIndex, 1);
  20711. }
  20712. meshIndex = light.excludedMeshes.indexOf(_this);
  20713. if (meshIndex !== -1) {
  20714. light.excludedMeshes.splice(meshIndex, 1);
  20715. }
  20716. // Shadow generators
  20717. var generator = light.getShadowGenerator();
  20718. if (generator) {
  20719. var shadowMap = generator.getShadowMap();
  20720. if (shadowMap && shadowMap.renderList) {
  20721. meshIndex = shadowMap.renderList.indexOf(_this);
  20722. if (meshIndex !== -1) {
  20723. shadowMap.renderList.splice(meshIndex, 1);
  20724. }
  20725. }
  20726. }
  20727. });
  20728. // Edges
  20729. if (this._edgesRenderer) {
  20730. this._edgesRenderer.dispose();
  20731. this._edgesRenderer = null;
  20732. }
  20733. // SubMeshes
  20734. if (this.getClassName() !== "InstancedMesh") {
  20735. this.releaseSubMeshes();
  20736. }
  20737. // Octree
  20738. var sceneOctree = this.getScene().selectionOctree;
  20739. if (sceneOctree !== undefined && sceneOctree !== null) {
  20740. var index = sceneOctree.dynamicContent.indexOf(this);
  20741. if (index !== -1) {
  20742. sceneOctree.dynamicContent.splice(index, 1);
  20743. }
  20744. }
  20745. // Query
  20746. var engine = this.getScene().getEngine();
  20747. if (this._occlusionQuery) {
  20748. this._isOcclusionQueryInProgress = false;
  20749. engine.deleteQuery(this._occlusionQuery);
  20750. this._occlusionQuery = null;
  20751. }
  20752. // Engine
  20753. engine.wipeCaches();
  20754. // Remove from scene
  20755. this.getScene().removeMesh(this);
  20756. if (disposeMaterialAndTextures) {
  20757. if (this.material) {
  20758. this.material.dispose(false, true);
  20759. }
  20760. }
  20761. if (!doNotRecurse) {
  20762. // Particles
  20763. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20764. if (this.getScene().particleSystems[index].emitter === this) {
  20765. this.getScene().particleSystems[index].dispose();
  20766. index--;
  20767. }
  20768. }
  20769. }
  20770. // facet data
  20771. if (this._facetDataEnabled) {
  20772. this.disableFacetData();
  20773. }
  20774. this.onAfterWorldMatrixUpdateObservable.clear();
  20775. this.onCollideObservable.clear();
  20776. this.onCollisionPositionChangeObservable.clear();
  20777. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20778. };
  20779. /**
  20780. * Adds the passed mesh as a child to the current mesh
  20781. * @param mesh defines the child mesh
  20782. * @returns the current mesh
  20783. */
  20784. AbstractMesh.prototype.addChild = function (mesh) {
  20785. mesh.setParent(this);
  20786. return this;
  20787. };
  20788. /**
  20789. * Removes the passed mesh from the current mesh children list
  20790. * @param mesh defines the child mesh
  20791. * @returns the current mesh
  20792. */
  20793. AbstractMesh.prototype.removeChild = function (mesh) {
  20794. mesh.setParent(null);
  20795. return this;
  20796. };
  20797. // Facet data
  20798. /** @hidden */
  20799. AbstractMesh.prototype._initFacetData = function () {
  20800. if (!this._facetNormals) {
  20801. this._facetNormals = new Array();
  20802. }
  20803. if (!this._facetPositions) {
  20804. this._facetPositions = new Array();
  20805. }
  20806. if (!this._facetPartitioning) {
  20807. this._facetPartitioning = new Array();
  20808. }
  20809. this._facetNb = (this.getIndices().length / 3) | 0;
  20810. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20811. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20812. for (var f = 0; f < this._facetNb; f++) {
  20813. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20814. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20815. }
  20816. this._facetDataEnabled = true;
  20817. return this;
  20818. };
  20819. /**
  20820. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20821. * This method can be called within the render loop.
  20822. * 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
  20823. * @returns the current mesh
  20824. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20825. */
  20826. AbstractMesh.prototype.updateFacetData = function () {
  20827. if (!this._facetDataEnabled) {
  20828. this._initFacetData();
  20829. }
  20830. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20831. var indices = this.getIndices();
  20832. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20833. var bInfo = this.getBoundingInfo();
  20834. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20835. // init arrays, matrix and sort function on first call
  20836. this._facetDepthSortEnabled = true;
  20837. if (indices instanceof Uint16Array) {
  20838. this._depthSortedIndices = new Uint16Array(indices);
  20839. }
  20840. else if (indices instanceof Uint32Array) {
  20841. this._depthSortedIndices = new Uint32Array(indices);
  20842. }
  20843. else {
  20844. var needs32bits = false;
  20845. for (var i = 0; i < indices.length; i++) {
  20846. if (indices[i] > 65535) {
  20847. needs32bits = true;
  20848. break;
  20849. }
  20850. }
  20851. if (needs32bits) {
  20852. this._depthSortedIndices = new Uint32Array(indices);
  20853. }
  20854. else {
  20855. this._depthSortedIndices = new Uint16Array(indices);
  20856. }
  20857. }
  20858. this._facetDepthSortFunction = function (f1, f2) {
  20859. return (f2.sqDistance - f1.sqDistance);
  20860. };
  20861. if (!this._facetDepthSortFrom) {
  20862. var camera = this.getScene().activeCamera;
  20863. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20864. }
  20865. this._depthSortedFacets = [];
  20866. for (var f = 0; f < this._facetNb; f++) {
  20867. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20868. this._depthSortedFacets.push(depthSortedFacet);
  20869. }
  20870. this._invertedMatrix = BABYLON.Matrix.Identity();
  20871. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20872. }
  20873. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20874. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20875. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20876. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20877. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20878. this._subDiv.max = this._partitioningSubdivisions;
  20879. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20880. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20881. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20882. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20883. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20884. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20885. // set the parameters for ComputeNormals()
  20886. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20887. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20888. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20889. this._facetParameters.bInfo = bInfo;
  20890. this._facetParameters.bbSize = this._bbSize;
  20891. this._facetParameters.subDiv = this._subDiv;
  20892. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20893. this._facetParameters.depthSort = this._facetDepthSort;
  20894. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20895. this.computeWorldMatrix(true);
  20896. this._worldMatrix.invertToRef(this._invertedMatrix);
  20897. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20898. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20899. }
  20900. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20901. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20902. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20903. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20904. var l = (this._depthSortedIndices.length / 3) | 0;
  20905. for (var f = 0; f < l; f++) {
  20906. var sind = this._depthSortedFacets[f].ind;
  20907. this._depthSortedIndices[f * 3] = indices[sind];
  20908. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20909. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20910. }
  20911. this.updateIndices(this._depthSortedIndices);
  20912. }
  20913. return this;
  20914. };
  20915. /**
  20916. * Returns the facetLocalNormals array.
  20917. * The normals are expressed in the mesh local spac
  20918. * @returns an array of Vector3
  20919. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20920. */
  20921. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20922. if (!this._facetNormals) {
  20923. this.updateFacetData();
  20924. }
  20925. return this._facetNormals;
  20926. };
  20927. /**
  20928. * Returns the facetLocalPositions array.
  20929. * The facet positions are expressed in the mesh local space
  20930. * @returns an array of Vector3
  20931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20932. */
  20933. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20934. if (!this._facetPositions) {
  20935. this.updateFacetData();
  20936. }
  20937. return this._facetPositions;
  20938. };
  20939. /**
  20940. * Returns the facetLocalPartioning array
  20941. * @returns an array of array of numbers
  20942. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20943. */
  20944. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20945. if (!this._facetPartitioning) {
  20946. this.updateFacetData();
  20947. }
  20948. return this._facetPartitioning;
  20949. };
  20950. /**
  20951. * Returns the i-th facet position in the world system.
  20952. * This method allocates a new Vector3 per call
  20953. * @param i defines the facet index
  20954. * @returns a new Vector3
  20955. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20956. */
  20957. AbstractMesh.prototype.getFacetPosition = function (i) {
  20958. var pos = BABYLON.Vector3.Zero();
  20959. this.getFacetPositionToRef(i, pos);
  20960. return pos;
  20961. };
  20962. /**
  20963. * Sets the reference Vector3 with the i-th facet position in the world system
  20964. * @param i defines the facet index
  20965. * @param ref defines the target vector
  20966. * @returns the current mesh
  20967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20968. */
  20969. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20970. var localPos = (this.getFacetLocalPositions())[i];
  20971. var world = this.getWorldMatrix();
  20972. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20973. return this;
  20974. };
  20975. /**
  20976. * Returns the i-th facet normal in the world system.
  20977. * This method allocates a new Vector3 per call
  20978. * @param i defines the facet index
  20979. * @returns a new Vector3
  20980. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20981. */
  20982. AbstractMesh.prototype.getFacetNormal = function (i) {
  20983. var norm = BABYLON.Vector3.Zero();
  20984. this.getFacetNormalToRef(i, norm);
  20985. return norm;
  20986. };
  20987. /**
  20988. * Sets the reference Vector3 with the i-th facet normal in the world system
  20989. * @param i defines the facet index
  20990. * @param ref defines the target vector
  20991. * @returns the current mesh
  20992. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20993. */
  20994. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20995. var localNorm = (this.getFacetLocalNormals())[i];
  20996. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20997. return this;
  20998. };
  20999. /**
  21000. * 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)
  21001. * @param x defines x coordinate
  21002. * @param y defines y coordinate
  21003. * @param z defines z coordinate
  21004. * @returns the array of facet indexes
  21005. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21006. */
  21007. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21008. var bInfo = this.getBoundingInfo();
  21009. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21010. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21011. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21012. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21013. return null;
  21014. }
  21015. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21016. };
  21017. /**
  21018. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21019. * @param projected sets as the (x,y,z) world projection on the facet
  21020. * @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
  21021. * @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
  21022. * @param x defines x coordinate
  21023. * @param y defines y coordinate
  21024. * @param z defines z coordinate
  21025. * @returns the face index if found (or null instead)
  21026. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21027. */
  21028. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21029. if (checkFace === void 0) { checkFace = false; }
  21030. if (facing === void 0) { facing = true; }
  21031. var world = this.getWorldMatrix();
  21032. var invMat = BABYLON.Tmp.Matrix[5];
  21033. world.invertToRef(invMat);
  21034. var invVect = BABYLON.Tmp.Vector3[8];
  21035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21036. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21037. if (projected) {
  21038. // tranform the local computed projected vector to world coordinates
  21039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21040. }
  21041. return closest;
  21042. };
  21043. /**
  21044. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21045. * @param projected sets as the (x,y,z) local projection on the facet
  21046. * @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
  21047. * @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
  21048. * @param x defines x coordinate
  21049. * @param y defines y coordinate
  21050. * @param z defines z coordinate
  21051. * @returns the face index if found (or null instead)
  21052. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21053. */
  21054. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21055. if (checkFace === void 0) { checkFace = false; }
  21056. if (facing === void 0) { facing = true; }
  21057. var closest = null;
  21058. var tmpx = 0.0;
  21059. var tmpy = 0.0;
  21060. var tmpz = 0.0;
  21061. var d = 0.0; // tmp dot facet normal * facet position
  21062. var t0 = 0.0;
  21063. var projx = 0.0;
  21064. var projy = 0.0;
  21065. var projz = 0.0;
  21066. // Get all the facets in the same partitioning block than (x, y, z)
  21067. var facetPositions = this.getFacetLocalPositions();
  21068. var facetNormals = this.getFacetLocalNormals();
  21069. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21070. if (!facetsInBlock) {
  21071. return null;
  21072. }
  21073. // Get the closest facet to (x, y, z)
  21074. var shortest = Number.MAX_VALUE; // init distance vars
  21075. var tmpDistance = shortest;
  21076. var fib; // current facet in the block
  21077. var norm; // current facet normal
  21078. var p0; // current facet barycenter position
  21079. // loop on all the facets in the current partitioning block
  21080. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21081. fib = facetsInBlock[idx];
  21082. norm = facetNormals[fib];
  21083. p0 = facetPositions[fib];
  21084. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21085. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21086. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21087. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21088. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21089. projx = x + norm.x * t0;
  21090. projy = y + norm.y * t0;
  21091. projz = z + norm.z * t0;
  21092. tmpx = projx - x;
  21093. tmpy = projy - y;
  21094. tmpz = projz - z;
  21095. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21096. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21097. shortest = tmpDistance;
  21098. closest = fib;
  21099. if (projected) {
  21100. projected.x = projx;
  21101. projected.y = projy;
  21102. projected.z = projz;
  21103. }
  21104. }
  21105. }
  21106. }
  21107. return closest;
  21108. };
  21109. /**
  21110. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21111. * @returns the parameters
  21112. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21113. */
  21114. AbstractMesh.prototype.getFacetDataParameters = function () {
  21115. return this._facetParameters;
  21116. };
  21117. /**
  21118. * Disables the feature FacetData and frees the related memory
  21119. * @returns the current mesh
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21121. */
  21122. AbstractMesh.prototype.disableFacetData = function () {
  21123. if (this._facetDataEnabled) {
  21124. this._facetDataEnabled = false;
  21125. this._facetPositions = new Array();
  21126. this._facetNormals = new Array();
  21127. this._facetPartitioning = new Array();
  21128. this._facetParameters = null;
  21129. this._depthSortedIndices = new Uint32Array(0);
  21130. }
  21131. return this;
  21132. };
  21133. /**
  21134. * Updates the AbstractMesh indices array
  21135. * @param indices defines the data source
  21136. * @returns the current mesh
  21137. */
  21138. AbstractMesh.prototype.updateIndices = function (indices) {
  21139. return this;
  21140. };
  21141. /**
  21142. * Creates new normals data for the mesh
  21143. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21144. * @returns the current mesh
  21145. */
  21146. AbstractMesh.prototype.createNormals = function (updatable) {
  21147. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21148. var indices = this.getIndices();
  21149. var normals;
  21150. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21151. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21152. }
  21153. else {
  21154. normals = [];
  21155. }
  21156. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21157. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21158. return this;
  21159. };
  21160. /**
  21161. * Align the mesh with a normal
  21162. * @param normal defines the normal to use
  21163. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21164. * @returns the current mesh
  21165. */
  21166. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21167. if (!upDirection) {
  21168. upDirection = BABYLON.Axis.Y;
  21169. }
  21170. var axisX = BABYLON.Tmp.Vector3[0];
  21171. var axisZ = BABYLON.Tmp.Vector3[1];
  21172. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21173. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21174. if (this.rotationQuaternion) {
  21175. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21176. }
  21177. else {
  21178. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21179. }
  21180. return this;
  21181. };
  21182. /** @hidden */
  21183. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21184. this._isOccluded = false;
  21185. };
  21186. /** No occlusion */
  21187. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21188. /** Occlusion set to optimisitic */
  21189. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21190. /** Occlusion set to strict */
  21191. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21192. /** Use an accurante occlusion algorithm */
  21193. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21194. /** Use a conservative occlusion algorithm */
  21195. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21196. return AbstractMesh;
  21197. }(BABYLON.TransformNode));
  21198. BABYLON.AbstractMesh = AbstractMesh;
  21199. })(BABYLON || (BABYLON = {}));
  21200. //# sourceMappingURL=babylon.abstractMesh.js.map
  21201. var BABYLON;
  21202. (function (BABYLON) {
  21203. /**
  21204. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21205. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21206. * 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.
  21207. */
  21208. var Light = /** @class */ (function (_super) {
  21209. __extends(Light, _super);
  21210. /**
  21211. * Creates a Light object in the scene.
  21212. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21213. * @param name The firendly name of the light
  21214. * @param scene The scene the light belongs too
  21215. */
  21216. function Light(name, scene) {
  21217. var _this = _super.call(this, name, scene) || this;
  21218. /**
  21219. * Diffuse gives the basic color to an object.
  21220. */
  21221. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21222. /**
  21223. * Specular produces a highlight color on an object.
  21224. * Note: This is note affecting PBR materials.
  21225. */
  21226. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21227. /**
  21228. * Strength of the light.
  21229. * Note: By default it is define in the framework own unit.
  21230. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21231. */
  21232. _this.intensity = 1.0;
  21233. /**
  21234. * Defines how far from the source the light is impacting in scene units.
  21235. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21236. */
  21237. _this.range = Number.MAX_VALUE;
  21238. /**
  21239. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21240. * of light.
  21241. */
  21242. _this._photometricScale = 1.0;
  21243. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21244. _this._radius = 0.00001;
  21245. /**
  21246. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21247. * exceeding the number allowed of the materials.
  21248. */
  21249. _this.renderPriority = 0;
  21250. _this._shadowEnabled = true;
  21251. _this._excludeWithLayerMask = 0;
  21252. _this._includeOnlyWithLayerMask = 0;
  21253. _this._lightmapMode = 0;
  21254. /**
  21255. * @hidden Internal use only.
  21256. */
  21257. _this._excludedMeshesIds = new Array();
  21258. /**
  21259. * @hidden Internal use only.
  21260. */
  21261. _this._includedOnlyMeshesIds = new Array();
  21262. _this.getScene().addLight(_this);
  21263. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21264. _this._buildUniformLayout();
  21265. _this.includedOnlyMeshes = new Array();
  21266. _this.excludedMeshes = new Array();
  21267. _this._resyncMeshes();
  21268. return _this;
  21269. }
  21270. Object.defineProperty(Light.prototype, "intensityMode", {
  21271. /**
  21272. * Gets the photometric scale used to interpret the intensity.
  21273. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21274. */
  21275. get: function () {
  21276. return this._intensityMode;
  21277. },
  21278. /**
  21279. * Sets the photometric scale used to interpret the intensity.
  21280. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21281. */
  21282. set: function (value) {
  21283. this._intensityMode = value;
  21284. this._computePhotometricScale();
  21285. },
  21286. enumerable: true,
  21287. configurable: true
  21288. });
  21289. ;
  21290. ;
  21291. Object.defineProperty(Light.prototype, "radius", {
  21292. /**
  21293. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21294. */
  21295. get: function () {
  21296. return this._radius;
  21297. },
  21298. /**
  21299. * sets the light radius used by PBR Materials to simulate soft area lights.
  21300. */
  21301. set: function (value) {
  21302. this._radius = value;
  21303. this._computePhotometricScale();
  21304. },
  21305. enumerable: true,
  21306. configurable: true
  21307. });
  21308. ;
  21309. ;
  21310. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21311. /**
  21312. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21313. * the current shadow generator.
  21314. */
  21315. get: function () {
  21316. return this._shadowEnabled;
  21317. },
  21318. /**
  21319. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21320. * the current shadow generator.
  21321. */
  21322. set: function (value) {
  21323. if (this._shadowEnabled === value) {
  21324. return;
  21325. }
  21326. this._shadowEnabled = value;
  21327. this._markMeshesAsLightDirty();
  21328. },
  21329. enumerable: true,
  21330. configurable: true
  21331. });
  21332. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21333. /**
  21334. * Gets the only meshes impacted by this light.
  21335. */
  21336. get: function () {
  21337. return this._includedOnlyMeshes;
  21338. },
  21339. /**
  21340. * Sets the only meshes impacted by this light.
  21341. */
  21342. set: function (value) {
  21343. this._includedOnlyMeshes = value;
  21344. this._hookArrayForIncludedOnly(value);
  21345. },
  21346. enumerable: true,
  21347. configurable: true
  21348. });
  21349. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21350. /**
  21351. * Gets the meshes not impacted by this light.
  21352. */
  21353. get: function () {
  21354. return this._excludedMeshes;
  21355. },
  21356. /**
  21357. * Sets the meshes not impacted by this light.
  21358. */
  21359. set: function (value) {
  21360. this._excludedMeshes = value;
  21361. this._hookArrayForExcluded(value);
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21367. /**
  21368. * Gets the layer id use to find what meshes are not impacted by the light.
  21369. * Inactive if 0
  21370. */
  21371. get: function () {
  21372. return this._excludeWithLayerMask;
  21373. },
  21374. /**
  21375. * Sets the layer id use to find what meshes are not impacted by the light.
  21376. * Inactive if 0
  21377. */
  21378. set: function (value) {
  21379. this._excludeWithLayerMask = value;
  21380. this._resyncMeshes();
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21386. /**
  21387. * Gets the layer id use to find what meshes are impacted by the light.
  21388. * Inactive if 0
  21389. */
  21390. get: function () {
  21391. return this._includeOnlyWithLayerMask;
  21392. },
  21393. /**
  21394. * Sets the layer id use to find what meshes are impacted by the light.
  21395. * Inactive if 0
  21396. */
  21397. set: function (value) {
  21398. this._includeOnlyWithLayerMask = value;
  21399. this._resyncMeshes();
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Object.defineProperty(Light.prototype, "lightmapMode", {
  21405. /**
  21406. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21407. */
  21408. get: function () {
  21409. return this._lightmapMode;
  21410. },
  21411. /**
  21412. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21413. */
  21414. set: function (value) {
  21415. if (this._lightmapMode === value) {
  21416. return;
  21417. }
  21418. this._lightmapMode = value;
  21419. this._markMeshesAsLightDirty();
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. /**
  21425. * Returns the string "Light".
  21426. * @returns the class name
  21427. */
  21428. Light.prototype.getClassName = function () {
  21429. return "Light";
  21430. };
  21431. /**
  21432. * Converts the light information to a readable string for debug purpose.
  21433. * @param fullDetails Supports for multiple levels of logging within scene loading
  21434. * @returns the human readable light info
  21435. */
  21436. Light.prototype.toString = function (fullDetails) {
  21437. var ret = "Name: " + this.name;
  21438. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21439. if (this.animations) {
  21440. for (var i = 0; i < this.animations.length; i++) {
  21441. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21442. }
  21443. }
  21444. if (fullDetails) {
  21445. }
  21446. return ret;
  21447. };
  21448. /**
  21449. * Set the enabled state of this node.
  21450. * @param value - the new enabled state
  21451. */
  21452. Light.prototype.setEnabled = function (value) {
  21453. _super.prototype.setEnabled.call(this, value);
  21454. this._resyncMeshes();
  21455. };
  21456. /**
  21457. * Returns the Light associated shadow generator if any.
  21458. * @return the associated shadow generator.
  21459. */
  21460. Light.prototype.getShadowGenerator = function () {
  21461. return this._shadowGenerator;
  21462. };
  21463. /**
  21464. * Returns a Vector3, the absolute light position in the World.
  21465. * @returns the world space position of the light
  21466. */
  21467. Light.prototype.getAbsolutePosition = function () {
  21468. return BABYLON.Vector3.Zero();
  21469. };
  21470. /**
  21471. * Specifies if the light will affect the passed mesh.
  21472. * @param mesh The mesh to test against the light
  21473. * @return true the mesh is affected otherwise, false.
  21474. */
  21475. Light.prototype.canAffectMesh = function (mesh) {
  21476. if (!mesh) {
  21477. return true;
  21478. }
  21479. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21480. return false;
  21481. }
  21482. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21483. return false;
  21484. }
  21485. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21486. return false;
  21487. }
  21488. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21489. return false;
  21490. }
  21491. return true;
  21492. };
  21493. /**
  21494. * Computes and Returns the light World matrix.
  21495. * @returns the world matrix
  21496. */
  21497. Light.prototype.getWorldMatrix = function () {
  21498. this._currentRenderId = this.getScene().getRenderId();
  21499. this._childRenderId = this._currentRenderId;
  21500. var worldMatrix = this._getWorldMatrix();
  21501. if (this.parent && this.parent.getWorldMatrix) {
  21502. if (!this._parentedWorldMatrix) {
  21503. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21504. }
  21505. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21506. this._markSyncedWithParent();
  21507. return this._parentedWorldMatrix;
  21508. }
  21509. return worldMatrix;
  21510. };
  21511. /**
  21512. * Sort function to order lights for rendering.
  21513. * @param a First Light object to compare to second.
  21514. * @param b Second Light object to compare first.
  21515. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21516. */
  21517. Light.CompareLightsPriority = function (a, b) {
  21518. //shadow-casting lights have priority over non-shadow-casting lights
  21519. //the renderPrioirty is a secondary sort criterion
  21520. if (a.shadowEnabled !== b.shadowEnabled) {
  21521. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21522. }
  21523. return b.renderPriority - a.renderPriority;
  21524. };
  21525. /**
  21526. * Releases resources associated with this node.
  21527. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21528. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21529. */
  21530. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21531. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21532. if (this._shadowGenerator) {
  21533. this._shadowGenerator.dispose();
  21534. this._shadowGenerator = null;
  21535. }
  21536. // Animations
  21537. this.getScene().stopAnimation(this);
  21538. // Remove from meshes
  21539. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21540. var mesh = _a[_i];
  21541. mesh._removeLightSource(this);
  21542. }
  21543. this._uniformBuffer.dispose();
  21544. // Remove from scene
  21545. this.getScene().removeLight(this);
  21546. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21547. };
  21548. /**
  21549. * Returns the light type ID (integer).
  21550. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21551. */
  21552. Light.prototype.getTypeID = function () {
  21553. return 0;
  21554. };
  21555. /**
  21556. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21557. * @returns the scaled intensity in intensity mode unit
  21558. */
  21559. Light.prototype.getScaledIntensity = function () {
  21560. return this._photometricScale * this.intensity;
  21561. };
  21562. /**
  21563. * Returns a new Light object, named "name", from the current one.
  21564. * @param name The name of the cloned light
  21565. * @returns the new created light
  21566. */
  21567. Light.prototype.clone = function (name) {
  21568. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21569. if (!constructor) {
  21570. return null;
  21571. }
  21572. return BABYLON.SerializationHelper.Clone(constructor, this);
  21573. };
  21574. /**
  21575. * Serializes the current light into a Serialization object.
  21576. * @returns the serialized object.
  21577. */
  21578. Light.prototype.serialize = function () {
  21579. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21580. // Type
  21581. serializationObject.type = this.getTypeID();
  21582. // Parent
  21583. if (this.parent) {
  21584. serializationObject.parentId = this.parent.id;
  21585. }
  21586. // Inclusion / exclusions
  21587. if (this.excludedMeshes.length > 0) {
  21588. serializationObject.excludedMeshesIds = [];
  21589. this.excludedMeshes.forEach(function (mesh) {
  21590. serializationObject.excludedMeshesIds.push(mesh.id);
  21591. });
  21592. }
  21593. if (this.includedOnlyMeshes.length > 0) {
  21594. serializationObject.includedOnlyMeshesIds = [];
  21595. this.includedOnlyMeshes.forEach(function (mesh) {
  21596. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21597. });
  21598. }
  21599. // Animations
  21600. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21601. serializationObject.ranges = this.serializeAnimationRanges();
  21602. return serializationObject;
  21603. };
  21604. /**
  21605. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21606. * This new light is named "name" and added to the passed scene.
  21607. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21608. * @param name The friendly name of the light
  21609. * @param scene The scene the new light will belong to
  21610. * @returns the constructor function
  21611. */
  21612. Light.GetConstructorFromName = function (type, name, scene) {
  21613. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21614. if (constructorFunc) {
  21615. return constructorFunc;
  21616. }
  21617. // Default to no light for none present once.
  21618. return null;
  21619. };
  21620. /**
  21621. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21622. * @param parsedLight The JSON representation of the light
  21623. * @param scene The scene to create the parsed light in
  21624. * @returns the created light after parsing
  21625. */
  21626. Light.Parse = function (parsedLight, scene) {
  21627. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21628. if (!constructor) {
  21629. return null;
  21630. }
  21631. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21632. // Inclusion / exclusions
  21633. if (parsedLight.excludedMeshesIds) {
  21634. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21635. }
  21636. if (parsedLight.includedOnlyMeshesIds) {
  21637. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21638. }
  21639. // Parent
  21640. if (parsedLight.parentId) {
  21641. light._waitingParentId = parsedLight.parentId;
  21642. }
  21643. // Animations
  21644. if (parsedLight.animations) {
  21645. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21646. var parsedAnimation = parsedLight.animations[animationIndex];
  21647. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21648. }
  21649. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21650. }
  21651. if (parsedLight.autoAnimate) {
  21652. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21653. }
  21654. return light;
  21655. };
  21656. Light.prototype._hookArrayForExcluded = function (array) {
  21657. var _this = this;
  21658. var oldPush = array.push;
  21659. array.push = function () {
  21660. var items = [];
  21661. for (var _i = 0; _i < arguments.length; _i++) {
  21662. items[_i] = arguments[_i];
  21663. }
  21664. var result = oldPush.apply(array, items);
  21665. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21666. var item = items_1[_a];
  21667. item._resyncLighSource(_this);
  21668. }
  21669. return result;
  21670. };
  21671. var oldSplice = array.splice;
  21672. array.splice = function (index, deleteCount) {
  21673. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21674. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21675. var item = deleted_1[_i];
  21676. item._resyncLighSource(_this);
  21677. }
  21678. return deleted;
  21679. };
  21680. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21681. var item = array_1[_i];
  21682. item._resyncLighSource(this);
  21683. }
  21684. };
  21685. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21686. var _this = this;
  21687. var oldPush = array.push;
  21688. array.push = function () {
  21689. var items = [];
  21690. for (var _i = 0; _i < arguments.length; _i++) {
  21691. items[_i] = arguments[_i];
  21692. }
  21693. var result = oldPush.apply(array, items);
  21694. _this._resyncMeshes();
  21695. return result;
  21696. };
  21697. var oldSplice = array.splice;
  21698. array.splice = function (index, deleteCount) {
  21699. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21700. _this._resyncMeshes();
  21701. return deleted;
  21702. };
  21703. this._resyncMeshes();
  21704. };
  21705. Light.prototype._resyncMeshes = function () {
  21706. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21707. var mesh = _a[_i];
  21708. mesh._resyncLighSource(this);
  21709. }
  21710. };
  21711. /**
  21712. * Forces the meshes to update their light related information in their rendering used effects
  21713. * @hidden Internal Use Only
  21714. */
  21715. Light.prototype._markMeshesAsLightDirty = function () {
  21716. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21717. var mesh = _a[_i];
  21718. if (mesh._lightSources.indexOf(this) !== -1) {
  21719. mesh._markSubMeshesAsLightDirty();
  21720. }
  21721. }
  21722. };
  21723. /**
  21724. * Recomputes the cached photometric scale if needed.
  21725. */
  21726. Light.prototype._computePhotometricScale = function () {
  21727. this._photometricScale = this._getPhotometricScale();
  21728. this.getScene().resetCachedMaterial();
  21729. };
  21730. /**
  21731. * Returns the Photometric Scale according to the light type and intensity mode.
  21732. */
  21733. Light.prototype._getPhotometricScale = function () {
  21734. var photometricScale = 0.0;
  21735. var lightTypeID = this.getTypeID();
  21736. //get photometric mode
  21737. var photometricMode = this.intensityMode;
  21738. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21739. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21740. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21741. }
  21742. else {
  21743. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21744. }
  21745. }
  21746. //compute photometric scale
  21747. switch (lightTypeID) {
  21748. case Light.LIGHTTYPEID_POINTLIGHT:
  21749. case Light.LIGHTTYPEID_SPOTLIGHT:
  21750. switch (photometricMode) {
  21751. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21752. photometricScale = 1.0 / (4.0 * Math.PI);
  21753. break;
  21754. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21755. photometricScale = 1.0;
  21756. break;
  21757. case Light.INTENSITYMODE_LUMINANCE:
  21758. photometricScale = this.radius * this.radius;
  21759. break;
  21760. }
  21761. break;
  21762. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21763. switch (photometricMode) {
  21764. case Light.INTENSITYMODE_ILLUMINANCE:
  21765. photometricScale = 1.0;
  21766. break;
  21767. case Light.INTENSITYMODE_LUMINANCE:
  21768. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21769. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21770. var apexAngleRadians = this.radius;
  21771. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21772. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21773. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21774. photometricScale = solidAngle;
  21775. break;
  21776. }
  21777. break;
  21778. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21779. // No fall off in hemisperic light.
  21780. photometricScale = 1.0;
  21781. break;
  21782. }
  21783. return photometricScale;
  21784. };
  21785. /**
  21786. * Reorder the light in the scene according to their defined priority.
  21787. * @hidden Internal Use Only
  21788. */
  21789. Light.prototype._reorderLightsInScene = function () {
  21790. var scene = this.getScene();
  21791. if (this._renderPriority != 0) {
  21792. scene.requireLightSorting = true;
  21793. }
  21794. this.getScene().sortLightsByPriority();
  21795. };
  21796. //lightmapMode Consts
  21797. /**
  21798. * If every light affecting the material is in this lightmapMode,
  21799. * material.lightmapTexture adds or multiplies
  21800. * (depends on material.useLightmapAsShadowmap)
  21801. * after every other light calculations.
  21802. */
  21803. Light.LIGHTMAP_DEFAULT = 0;
  21804. /**
  21805. * material.lightmapTexture as only diffuse lighting from this light
  21806. * adds only specular lighting from this light
  21807. * adds dynamic shadows
  21808. */
  21809. Light.LIGHTMAP_SPECULAR = 1;
  21810. /**
  21811. * material.lightmapTexture as only lighting
  21812. * no light calculation from this light
  21813. * only adds dynamic shadows from this light
  21814. */
  21815. Light.LIGHTMAP_SHADOWSONLY = 2;
  21816. // Intensity Mode Consts
  21817. /**
  21818. * Each light type uses the default quantity according to its type:
  21819. * point/spot lights use luminous intensity
  21820. * directional lights use illuminance
  21821. */
  21822. Light.INTENSITYMODE_AUTOMATIC = 0;
  21823. /**
  21824. * lumen (lm)
  21825. */
  21826. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21827. /**
  21828. * candela (lm/sr)
  21829. */
  21830. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21831. /**
  21832. * lux (lm/m^2)
  21833. */
  21834. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21835. /**
  21836. * nit (cd/m^2)
  21837. */
  21838. Light.INTENSITYMODE_LUMINANCE = 4;
  21839. // Light types ids const.
  21840. /**
  21841. * Light type const id of the point light.
  21842. */
  21843. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21844. /**
  21845. * Light type const id of the directional light.
  21846. */
  21847. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21848. /**
  21849. * Light type const id of the spot light.
  21850. */
  21851. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21852. /**
  21853. * Light type const id of the hemispheric light.
  21854. */
  21855. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21856. __decorate([
  21857. BABYLON.serializeAsColor3()
  21858. ], Light.prototype, "diffuse", void 0);
  21859. __decorate([
  21860. BABYLON.serializeAsColor3()
  21861. ], Light.prototype, "specular", void 0);
  21862. __decorate([
  21863. BABYLON.serialize()
  21864. ], Light.prototype, "intensity", void 0);
  21865. __decorate([
  21866. BABYLON.serialize()
  21867. ], Light.prototype, "range", void 0);
  21868. __decorate([
  21869. BABYLON.serialize()
  21870. ], Light.prototype, "intensityMode", null);
  21871. __decorate([
  21872. BABYLON.serialize()
  21873. ], Light.prototype, "radius", null);
  21874. __decorate([
  21875. BABYLON.serialize()
  21876. ], Light.prototype, "_renderPriority", void 0);
  21877. __decorate([
  21878. BABYLON.expandToProperty("_reorderLightsInScene")
  21879. ], Light.prototype, "renderPriority", void 0);
  21880. __decorate([
  21881. BABYLON.serialize("shadowEnabled")
  21882. ], Light.prototype, "_shadowEnabled", void 0);
  21883. __decorate([
  21884. BABYLON.serialize("excludeWithLayerMask")
  21885. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21886. __decorate([
  21887. BABYLON.serialize("includeOnlyWithLayerMask")
  21888. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21889. __decorate([
  21890. BABYLON.serialize("lightmapMode")
  21891. ], Light.prototype, "_lightmapMode", void 0);
  21892. return Light;
  21893. }(BABYLON.Node));
  21894. BABYLON.Light = Light;
  21895. })(BABYLON || (BABYLON = {}));
  21896. //# sourceMappingURL=babylon.light.js.map
  21897. var BABYLON;
  21898. (function (BABYLON) {
  21899. var Camera = /** @class */ (function (_super) {
  21900. __extends(Camera, _super);
  21901. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21902. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21903. var _this = _super.call(this, name, scene) || this;
  21904. /**
  21905. * The vector the camera should consider as up.
  21906. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21907. */
  21908. _this.upVector = BABYLON.Vector3.Up();
  21909. _this.orthoLeft = null;
  21910. _this.orthoRight = null;
  21911. _this.orthoBottom = null;
  21912. _this.orthoTop = null;
  21913. /**
  21914. * FOV is set in Radians. (default is 0.8)
  21915. */
  21916. _this.fov = 0.8;
  21917. _this.minZ = 1;
  21918. _this.maxZ = 10000.0;
  21919. _this.inertia = 0.9;
  21920. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21921. _this.isIntermediate = false;
  21922. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21923. /**
  21924. * Restricts the camera to viewing objects with the same layerMask.
  21925. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21926. */
  21927. _this.layerMask = 0x0FFFFFFF;
  21928. /**
  21929. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21930. */
  21931. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21932. // Camera rig members
  21933. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21934. _this._rigCameras = new Array();
  21935. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21936. _this._skipRendering = false;
  21937. _this.customRenderTargets = new Array();
  21938. // Observables
  21939. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21940. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21941. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21942. _this.onRestoreStateObservable = new BABYLON.Observable();
  21943. // Cache
  21944. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21945. _this._projectionMatrix = new BABYLON.Matrix();
  21946. _this._doNotComputeProjectionMatrix = false;
  21947. _this._worldMatrix = BABYLON.Matrix.Identity();
  21948. _this._postProcesses = new Array();
  21949. _this._transformMatrix = BABYLON.Matrix.Zero();
  21950. _this._activeMeshes = new BABYLON.SmartArray(256);
  21951. _this._globalPosition = BABYLON.Vector3.Zero();
  21952. _this._refreshFrustumPlanes = true;
  21953. _this.getScene().addCamera(_this);
  21954. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21955. _this.getScene().activeCamera = _this;
  21956. }
  21957. _this.position = position;
  21958. return _this;
  21959. }
  21960. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21961. get: function () {
  21962. return Camera._PERSPECTIVE_CAMERA;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21968. get: function () {
  21969. return Camera._ORTHOGRAPHIC_CAMERA;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21975. /**
  21976. * This is the default FOV mode for perspective cameras.
  21977. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21978. *
  21979. */
  21980. get: function () {
  21981. return Camera._FOVMODE_VERTICAL_FIXED;
  21982. },
  21983. enumerable: true,
  21984. configurable: true
  21985. });
  21986. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21987. /**
  21988. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21989. *
  21990. */
  21991. get: function () {
  21992. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21998. get: function () {
  21999. return Camera._RIG_MODE_NONE;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22005. get: function () {
  22006. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22012. get: function () {
  22013. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22019. get: function () {
  22020. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22026. get: function () {
  22027. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22028. },
  22029. enumerable: true,
  22030. configurable: true
  22031. });
  22032. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22033. get: function () {
  22034. return Camera._RIG_MODE_VR;
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22040. get: function () {
  22041. return Camera._RIG_MODE_WEBVR;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. /**
  22047. * Store current camera state (fov, position, etc..)
  22048. */
  22049. Camera.prototype.storeState = function () {
  22050. this._stateStored = true;
  22051. this._storedFov = this.fov;
  22052. return this;
  22053. };
  22054. /**
  22055. * Restores the camera state values if it has been stored. You must call storeState() first
  22056. */
  22057. Camera.prototype._restoreStateValues = function () {
  22058. if (!this._stateStored) {
  22059. return false;
  22060. }
  22061. this.fov = this._storedFov;
  22062. return true;
  22063. };
  22064. /**
  22065. * Restored camera state. You must call storeState() first
  22066. */
  22067. Camera.prototype.restoreState = function () {
  22068. if (this._restoreStateValues()) {
  22069. this.onRestoreStateObservable.notifyObservers(this);
  22070. return true;
  22071. }
  22072. return false;
  22073. };
  22074. Camera.prototype.getClassName = function () {
  22075. return "Camera";
  22076. };
  22077. /**
  22078. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22079. */
  22080. Camera.prototype.toString = function (fullDetails) {
  22081. var ret = "Name: " + this.name;
  22082. ret += ", type: " + this.getClassName();
  22083. if (this.animations) {
  22084. for (var i = 0; i < this.animations.length; i++) {
  22085. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22086. }
  22087. }
  22088. if (fullDetails) {
  22089. }
  22090. return ret;
  22091. };
  22092. Object.defineProperty(Camera.prototype, "globalPosition", {
  22093. get: function () {
  22094. return this._globalPosition;
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Camera.prototype.getActiveMeshes = function () {
  22100. return this._activeMeshes;
  22101. };
  22102. Camera.prototype.isActiveMesh = function (mesh) {
  22103. return (this._activeMeshes.indexOf(mesh) !== -1);
  22104. };
  22105. /**
  22106. * Is this camera ready to be used/rendered
  22107. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22108. * @return true if the camera is ready
  22109. */
  22110. Camera.prototype.isReady = function (completeCheck) {
  22111. if (completeCheck === void 0) { completeCheck = false; }
  22112. if (completeCheck) {
  22113. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22114. var pp = _a[_i];
  22115. if (pp && !pp.isReady()) {
  22116. return false;
  22117. }
  22118. }
  22119. }
  22120. return _super.prototype.isReady.call(this, completeCheck);
  22121. };
  22122. //Cache
  22123. Camera.prototype._initCache = function () {
  22124. _super.prototype._initCache.call(this);
  22125. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22126. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22127. this._cache.mode = undefined;
  22128. this._cache.minZ = undefined;
  22129. this._cache.maxZ = undefined;
  22130. this._cache.fov = undefined;
  22131. this._cache.fovMode = undefined;
  22132. this._cache.aspectRatio = undefined;
  22133. this._cache.orthoLeft = undefined;
  22134. this._cache.orthoRight = undefined;
  22135. this._cache.orthoBottom = undefined;
  22136. this._cache.orthoTop = undefined;
  22137. this._cache.renderWidth = undefined;
  22138. this._cache.renderHeight = undefined;
  22139. };
  22140. Camera.prototype._updateCache = function (ignoreParentClass) {
  22141. if (!ignoreParentClass) {
  22142. _super.prototype._updateCache.call(this);
  22143. }
  22144. this._cache.position.copyFrom(this.position);
  22145. this._cache.upVector.copyFrom(this.upVector);
  22146. };
  22147. // Synchronized
  22148. Camera.prototype._isSynchronized = function () {
  22149. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22150. };
  22151. Camera.prototype._isSynchronizedViewMatrix = function () {
  22152. if (!_super.prototype._isSynchronized.call(this))
  22153. return false;
  22154. return this._cache.position.equals(this.position)
  22155. && this._cache.upVector.equals(this.upVector)
  22156. && this.isSynchronizedWithParent();
  22157. };
  22158. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22159. var check = this._cache.mode === this.mode
  22160. && this._cache.minZ === this.minZ
  22161. && this._cache.maxZ === this.maxZ;
  22162. if (!check) {
  22163. return false;
  22164. }
  22165. var engine = this.getEngine();
  22166. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22167. check = this._cache.fov === this.fov
  22168. && this._cache.fovMode === this.fovMode
  22169. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22170. }
  22171. else {
  22172. check = this._cache.orthoLeft === this.orthoLeft
  22173. && this._cache.orthoRight === this.orthoRight
  22174. && this._cache.orthoBottom === this.orthoBottom
  22175. && this._cache.orthoTop === this.orthoTop
  22176. && this._cache.renderWidth === engine.getRenderWidth()
  22177. && this._cache.renderHeight === engine.getRenderHeight();
  22178. }
  22179. return check;
  22180. };
  22181. // Controls
  22182. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22183. };
  22184. Camera.prototype.detachControl = function (element) {
  22185. };
  22186. Camera.prototype.update = function () {
  22187. this._checkInputs();
  22188. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22189. this._updateRigCameras();
  22190. }
  22191. };
  22192. Camera.prototype._checkInputs = function () {
  22193. this.onAfterCheckInputsObservable.notifyObservers(this);
  22194. };
  22195. Object.defineProperty(Camera.prototype, "rigCameras", {
  22196. get: function () {
  22197. return this._rigCameras;
  22198. },
  22199. enumerable: true,
  22200. configurable: true
  22201. });
  22202. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22203. get: function () {
  22204. return this._rigPostProcess;
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. /**
  22210. * Internal, gets the first post proces.
  22211. * @returns the first post process to be run on this camera.
  22212. */
  22213. Camera.prototype._getFirstPostProcess = function () {
  22214. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22215. if (this._postProcesses[ppIndex] !== null) {
  22216. return this._postProcesses[ppIndex];
  22217. }
  22218. }
  22219. return null;
  22220. };
  22221. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22222. // invalidate framebuffer
  22223. var firstPostProcess = this._getFirstPostProcess();
  22224. if (firstPostProcess) {
  22225. firstPostProcess.markTextureDirty();
  22226. }
  22227. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22228. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22229. var cam = this._rigCameras[i];
  22230. var rigPostProcess = cam._rigPostProcess;
  22231. // for VR rig, there does not have to be a post process
  22232. if (rigPostProcess) {
  22233. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22234. if (isPass) {
  22235. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22236. cam.isIntermediate = this._postProcesses.length === 0;
  22237. }
  22238. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22239. rigPostProcess.markTextureDirty();
  22240. }
  22241. else {
  22242. cam._postProcesses = this._postProcesses.slice(0);
  22243. }
  22244. }
  22245. };
  22246. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22247. if (insertAt === void 0) { insertAt = null; }
  22248. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22249. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22250. return 0;
  22251. }
  22252. if (insertAt == null || insertAt < 0) {
  22253. this._postProcesses.push(postProcess);
  22254. }
  22255. else if (this._postProcesses[insertAt] === null) {
  22256. this._postProcesses[insertAt] = postProcess;
  22257. }
  22258. else {
  22259. this._postProcesses.splice(insertAt, 0, postProcess);
  22260. }
  22261. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22262. return this._postProcesses.indexOf(postProcess);
  22263. };
  22264. Camera.prototype.detachPostProcess = function (postProcess) {
  22265. var idx = this._postProcesses.indexOf(postProcess);
  22266. if (idx !== -1) {
  22267. this._postProcesses[idx] = null;
  22268. }
  22269. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22270. };
  22271. Camera.prototype.getWorldMatrix = function () {
  22272. if (this._isSynchronizedViewMatrix()) {
  22273. return this._worldMatrix;
  22274. }
  22275. // Getting the the view matrix will also compute the world matrix.
  22276. this.getViewMatrix();
  22277. return this._worldMatrix;
  22278. };
  22279. Camera.prototype._getViewMatrix = function () {
  22280. return BABYLON.Matrix.Identity();
  22281. };
  22282. Camera.prototype.getViewMatrix = function (force) {
  22283. if (!force && this._isSynchronizedViewMatrix()) {
  22284. return this._computedViewMatrix;
  22285. }
  22286. this.updateCache();
  22287. this._computedViewMatrix = this._getViewMatrix();
  22288. this._currentRenderId = this.getScene().getRenderId();
  22289. this._childRenderId = this._currentRenderId;
  22290. this._refreshFrustumPlanes = true;
  22291. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22292. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22293. }
  22294. this.onViewMatrixChangedObservable.notifyObservers(this);
  22295. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22296. return this._computedViewMatrix;
  22297. };
  22298. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22299. this._doNotComputeProjectionMatrix = true;
  22300. if (projection !== undefined) {
  22301. this._projectionMatrix = projection;
  22302. }
  22303. };
  22304. ;
  22305. Camera.prototype.unfreezeProjectionMatrix = function () {
  22306. this._doNotComputeProjectionMatrix = false;
  22307. };
  22308. ;
  22309. Camera.prototype.getProjectionMatrix = function (force) {
  22310. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22311. return this._projectionMatrix;
  22312. }
  22313. // Cache
  22314. this._cache.mode = this.mode;
  22315. this._cache.minZ = this.minZ;
  22316. this._cache.maxZ = this.maxZ;
  22317. // Matrix
  22318. this._refreshFrustumPlanes = true;
  22319. var engine = this.getEngine();
  22320. var scene = this.getScene();
  22321. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22322. this._cache.fov = this.fov;
  22323. this._cache.fovMode = this.fovMode;
  22324. this._cache.aspectRatio = engine.getAspectRatio(this);
  22325. if (this.minZ <= 0) {
  22326. this.minZ = 0.1;
  22327. }
  22328. if (scene.useRightHandedSystem) {
  22329. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22330. }
  22331. else {
  22332. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22333. }
  22334. }
  22335. else {
  22336. var halfWidth = engine.getRenderWidth() / 2.0;
  22337. var halfHeight = engine.getRenderHeight() / 2.0;
  22338. if (scene.useRightHandedSystem) {
  22339. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22340. }
  22341. else {
  22342. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22343. }
  22344. this._cache.orthoLeft = this.orthoLeft;
  22345. this._cache.orthoRight = this.orthoRight;
  22346. this._cache.orthoBottom = this.orthoBottom;
  22347. this._cache.orthoTop = this.orthoTop;
  22348. this._cache.renderWidth = engine.getRenderWidth();
  22349. this._cache.renderHeight = engine.getRenderHeight();
  22350. }
  22351. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22352. return this._projectionMatrix;
  22353. };
  22354. Camera.prototype.getTranformationMatrix = function () {
  22355. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22356. return this._transformMatrix;
  22357. };
  22358. Camera.prototype.updateFrustumPlanes = function () {
  22359. if (!this._refreshFrustumPlanes) {
  22360. return;
  22361. }
  22362. this.getTranformationMatrix();
  22363. if (!this._frustumPlanes) {
  22364. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22365. }
  22366. else {
  22367. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22368. }
  22369. this._refreshFrustumPlanes = false;
  22370. };
  22371. Camera.prototype.isInFrustum = function (target) {
  22372. this.updateFrustumPlanes();
  22373. return target.isInFrustum(this._frustumPlanes);
  22374. };
  22375. Camera.prototype.isCompletelyInFrustum = function (target) {
  22376. this.updateFrustumPlanes();
  22377. return target.isCompletelyInFrustum(this._frustumPlanes);
  22378. };
  22379. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22380. if (length === void 0) { length = 100; }
  22381. if (!transform) {
  22382. transform = this.getWorldMatrix();
  22383. }
  22384. if (!origin) {
  22385. origin = this.position;
  22386. }
  22387. var forward = new BABYLON.Vector3(0, 0, 1);
  22388. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22389. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22390. return new BABYLON.Ray(origin, direction, length);
  22391. };
  22392. /**
  22393. * Releases resources associated with this node.
  22394. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22395. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22396. */
  22397. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22398. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22399. // Observables
  22400. this.onViewMatrixChangedObservable.clear();
  22401. this.onProjectionMatrixChangedObservable.clear();
  22402. this.onAfterCheckInputsObservable.clear();
  22403. this.onRestoreStateObservable.clear();
  22404. // Inputs
  22405. if (this.inputs) {
  22406. this.inputs.clear();
  22407. }
  22408. // Animations
  22409. this.getScene().stopAnimation(this);
  22410. // Remove from scene
  22411. this.getScene().removeCamera(this);
  22412. while (this._rigCameras.length > 0) {
  22413. var camera = this._rigCameras.pop();
  22414. if (camera) {
  22415. camera.dispose();
  22416. }
  22417. }
  22418. // Postprocesses
  22419. if (this._rigPostProcess) {
  22420. this._rigPostProcess.dispose(this);
  22421. this._rigPostProcess = null;
  22422. this._postProcesses = [];
  22423. }
  22424. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22425. this._rigPostProcess = null;
  22426. this._postProcesses = [];
  22427. }
  22428. else {
  22429. var i = this._postProcesses.length;
  22430. while (--i >= 0) {
  22431. var postProcess = this._postProcesses[i];
  22432. if (postProcess) {
  22433. postProcess.dispose(this);
  22434. }
  22435. }
  22436. }
  22437. // Render targets
  22438. var i = this.customRenderTargets.length;
  22439. while (--i >= 0) {
  22440. this.customRenderTargets[i].dispose();
  22441. }
  22442. this.customRenderTargets = [];
  22443. // Active Meshes
  22444. this._activeMeshes.dispose();
  22445. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22446. };
  22447. Object.defineProperty(Camera.prototype, "leftCamera", {
  22448. // ---- Camera rigs section ----
  22449. get: function () {
  22450. if (this._rigCameras.length < 1) {
  22451. return null;
  22452. }
  22453. return this._rigCameras[0];
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Camera.prototype, "rightCamera", {
  22459. get: function () {
  22460. if (this._rigCameras.length < 2) {
  22461. return null;
  22462. }
  22463. return this._rigCameras[1];
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Camera.prototype.getLeftTarget = function () {
  22469. if (this._rigCameras.length < 1) {
  22470. return null;
  22471. }
  22472. return this._rigCameras[0].getTarget();
  22473. };
  22474. Camera.prototype.getRightTarget = function () {
  22475. if (this._rigCameras.length < 2) {
  22476. return null;
  22477. }
  22478. return this._rigCameras[1].getTarget();
  22479. };
  22480. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22481. if (this.cameraRigMode === mode) {
  22482. return;
  22483. }
  22484. while (this._rigCameras.length > 0) {
  22485. var camera = this._rigCameras.pop();
  22486. if (camera) {
  22487. camera.dispose();
  22488. }
  22489. }
  22490. this.cameraRigMode = mode;
  22491. this._cameraRigParams = {};
  22492. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22493. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22494. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22495. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22496. // create the rig cameras, unless none
  22497. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22498. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22499. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22500. if (leftCamera && rightCamera) {
  22501. this._rigCameras.push(leftCamera);
  22502. this._rigCameras.push(rightCamera);
  22503. }
  22504. }
  22505. switch (this.cameraRigMode) {
  22506. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22507. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22508. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22509. break;
  22510. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22511. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22512. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22513. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22514. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22515. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22516. break;
  22517. case Camera.RIG_MODE_VR:
  22518. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22519. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22520. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22521. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22522. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22523. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22524. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22525. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22526. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22527. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22528. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22529. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22530. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22531. if (metrics.compensateDistortion) {
  22532. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22533. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22534. }
  22535. break;
  22536. case Camera.RIG_MODE_WEBVR:
  22537. if (rigParams.vrDisplay) {
  22538. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22539. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22540. //Left eye
  22541. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22542. this._rigCameras[0].setCameraRigParameter("left", true);
  22543. //leaving this for future reference
  22544. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22545. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22546. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22547. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22548. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22549. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22550. this._rigCameras[0].parent = this;
  22551. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22552. //Right eye
  22553. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22554. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22555. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22556. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22557. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22558. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22559. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22560. this._rigCameras[1].parent = this;
  22561. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22562. if (Camera.UseAlternateWebVRRendering) {
  22563. this._rigCameras[1]._skipRendering = true;
  22564. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22565. }
  22566. }
  22567. break;
  22568. }
  22569. this._cascadePostProcessesToRigCams();
  22570. this.update();
  22571. };
  22572. Camera.prototype._getVRProjectionMatrix = function () {
  22573. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22574. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22575. return this._projectionMatrix;
  22576. };
  22577. Camera.prototype._updateCameraRotationMatrix = function () {
  22578. //Here for WebVR
  22579. };
  22580. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22581. //Here for WebVR
  22582. };
  22583. /**
  22584. * This function MUST be overwritten by the different WebVR cameras available.
  22585. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22586. */
  22587. Camera.prototype._getWebVRProjectionMatrix = function () {
  22588. return BABYLON.Matrix.Identity();
  22589. };
  22590. /**
  22591. * This function MUST be overwritten by the different WebVR cameras available.
  22592. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22593. */
  22594. Camera.prototype._getWebVRViewMatrix = function () {
  22595. return BABYLON.Matrix.Identity();
  22596. };
  22597. Camera.prototype.setCameraRigParameter = function (name, value) {
  22598. if (!this._cameraRigParams) {
  22599. this._cameraRigParams = {};
  22600. }
  22601. this._cameraRigParams[name] = value;
  22602. //provisionnally:
  22603. if (name === "interaxialDistance") {
  22604. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22605. }
  22606. };
  22607. /**
  22608. * needs to be overridden by children so sub has required properties to be copied
  22609. */
  22610. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22611. return null;
  22612. };
  22613. /**
  22614. * May need to be overridden by children
  22615. */
  22616. Camera.prototype._updateRigCameras = function () {
  22617. for (var i = 0; i < this._rigCameras.length; i++) {
  22618. this._rigCameras[i].minZ = this.minZ;
  22619. this._rigCameras[i].maxZ = this.maxZ;
  22620. this._rigCameras[i].fov = this.fov;
  22621. }
  22622. // only update viewport when ANAGLYPH
  22623. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22624. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22625. }
  22626. };
  22627. Camera.prototype._setupInputs = function () {
  22628. };
  22629. Camera.prototype.serialize = function () {
  22630. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22631. // Type
  22632. serializationObject.type = this.getClassName();
  22633. // Parent
  22634. if (this.parent) {
  22635. serializationObject.parentId = this.parent.id;
  22636. }
  22637. if (this.inputs) {
  22638. this.inputs.serialize(serializationObject);
  22639. }
  22640. // Animations
  22641. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22642. serializationObject.ranges = this.serializeAnimationRanges();
  22643. return serializationObject;
  22644. };
  22645. Camera.prototype.clone = function (name) {
  22646. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22647. };
  22648. Camera.prototype.getDirection = function (localAxis) {
  22649. var result = BABYLON.Vector3.Zero();
  22650. this.getDirectionToRef(localAxis, result);
  22651. return result;
  22652. };
  22653. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22654. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22655. };
  22656. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22657. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22658. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22659. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22660. interaxial_distance: interaxial_distance,
  22661. isStereoscopicSideBySide: isStereoscopicSideBySide
  22662. });
  22663. if (constructorFunc) {
  22664. return constructorFunc;
  22665. }
  22666. // Default to universal camera
  22667. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22668. };
  22669. Camera.prototype.computeWorldMatrix = function () {
  22670. return this.getWorldMatrix();
  22671. };
  22672. Camera.Parse = function (parsedCamera, scene) {
  22673. var type = parsedCamera.type;
  22674. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22675. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22676. // Parent
  22677. if (parsedCamera.parentId) {
  22678. camera._waitingParentId = parsedCamera.parentId;
  22679. }
  22680. //If camera has an input manager, let it parse inputs settings
  22681. if (camera.inputs) {
  22682. camera.inputs.parse(parsedCamera);
  22683. camera._setupInputs();
  22684. }
  22685. if (camera.setPosition) { // need to force position
  22686. camera.position.copyFromFloats(0, 0, 0);
  22687. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22688. }
  22689. // Target
  22690. if (parsedCamera.target) {
  22691. if (camera.setTarget) {
  22692. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22693. }
  22694. }
  22695. // Apply 3d rig, when found
  22696. if (parsedCamera.cameraRigMode) {
  22697. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22698. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22699. }
  22700. // Animations
  22701. if (parsedCamera.animations) {
  22702. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22703. var parsedAnimation = parsedCamera.animations[animationIndex];
  22704. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22705. }
  22706. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22707. }
  22708. if (parsedCamera.autoAnimate) {
  22709. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22710. }
  22711. return camera;
  22712. };
  22713. // Statics
  22714. Camera._PERSPECTIVE_CAMERA = 0;
  22715. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22716. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22717. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22718. Camera._RIG_MODE_NONE = 0;
  22719. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22720. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22721. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22722. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22723. Camera._RIG_MODE_VR = 20;
  22724. Camera._RIG_MODE_WEBVR = 21;
  22725. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22726. Camera.UseAlternateWebVRRendering = false;
  22727. __decorate([
  22728. BABYLON.serializeAsVector3()
  22729. ], Camera.prototype, "position", void 0);
  22730. __decorate([
  22731. BABYLON.serializeAsVector3()
  22732. ], Camera.prototype, "upVector", void 0);
  22733. __decorate([
  22734. BABYLON.serialize()
  22735. ], Camera.prototype, "orthoLeft", void 0);
  22736. __decorate([
  22737. BABYLON.serialize()
  22738. ], Camera.prototype, "orthoRight", void 0);
  22739. __decorate([
  22740. BABYLON.serialize()
  22741. ], Camera.prototype, "orthoBottom", void 0);
  22742. __decorate([
  22743. BABYLON.serialize()
  22744. ], Camera.prototype, "orthoTop", void 0);
  22745. __decorate([
  22746. BABYLON.serialize()
  22747. ], Camera.prototype, "fov", void 0);
  22748. __decorate([
  22749. BABYLON.serialize()
  22750. ], Camera.prototype, "minZ", void 0);
  22751. __decorate([
  22752. BABYLON.serialize()
  22753. ], Camera.prototype, "maxZ", void 0);
  22754. __decorate([
  22755. BABYLON.serialize()
  22756. ], Camera.prototype, "inertia", void 0);
  22757. __decorate([
  22758. BABYLON.serialize()
  22759. ], Camera.prototype, "mode", void 0);
  22760. __decorate([
  22761. BABYLON.serialize()
  22762. ], Camera.prototype, "layerMask", void 0);
  22763. __decorate([
  22764. BABYLON.serialize()
  22765. ], Camera.prototype, "fovMode", void 0);
  22766. __decorate([
  22767. BABYLON.serialize()
  22768. ], Camera.prototype, "cameraRigMode", void 0);
  22769. __decorate([
  22770. BABYLON.serialize()
  22771. ], Camera.prototype, "interaxialDistance", void 0);
  22772. __decorate([
  22773. BABYLON.serialize()
  22774. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22775. return Camera;
  22776. }(BABYLON.Node));
  22777. BABYLON.Camera = Camera;
  22778. })(BABYLON || (BABYLON = {}));
  22779. //# sourceMappingURL=babylon.camera.js.map
  22780. var BABYLON;
  22781. (function (BABYLON) {
  22782. var RenderingManager = /** @class */ (function () {
  22783. function RenderingManager(scene) {
  22784. this._renderingGroups = new Array();
  22785. this._autoClearDepthStencil = {};
  22786. this._customOpaqueSortCompareFn = {};
  22787. this._customAlphaTestSortCompareFn = {};
  22788. this._customTransparentSortCompareFn = {};
  22789. this._renderinGroupInfo = null;
  22790. this._scene = scene;
  22791. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22792. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22793. }
  22794. }
  22795. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22796. if (depth === void 0) { depth = true; }
  22797. if (stencil === void 0) { stencil = true; }
  22798. if (this._depthStencilBufferAlreadyCleaned) {
  22799. return;
  22800. }
  22801. this._scene.getEngine().clear(null, false, depth, stencil);
  22802. this._depthStencilBufferAlreadyCleaned = true;
  22803. };
  22804. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22805. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22806. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22807. var info = null;
  22808. if (observable) {
  22809. if (!this._renderinGroupInfo) {
  22810. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22811. }
  22812. info = this._renderinGroupInfo;
  22813. info.scene = this._scene;
  22814. info.camera = this._scene.activeCamera;
  22815. }
  22816. // Dispatch sprites
  22817. if (renderSprites) {
  22818. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22819. var manager = this._scene.spriteManagers[index];
  22820. this.dispatchSprites(manager);
  22821. }
  22822. }
  22823. // Render
  22824. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22825. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22826. var renderingGroup = this._renderingGroups[index];
  22827. if (!renderingGroup && !observable)
  22828. continue;
  22829. var renderingGroupMask = 0;
  22830. // Fire PRECLEAR stage
  22831. if (observable && info) {
  22832. renderingGroupMask = Math.pow(2, index);
  22833. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22834. info.renderingGroupId = index;
  22835. observable.notifyObservers(info, renderingGroupMask);
  22836. }
  22837. // Clear depth/stencil if needed
  22838. if (RenderingManager.AUTOCLEAR) {
  22839. var autoClear = this._autoClearDepthStencil[index];
  22840. if (autoClear && autoClear.autoClear) {
  22841. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22842. }
  22843. }
  22844. if (observable && info) {
  22845. // Fire PREOPAQUE stage
  22846. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22847. observable.notifyObservers(info, renderingGroupMask);
  22848. // Fire PRETRANSPARENT stage
  22849. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22850. observable.notifyObservers(info, renderingGroupMask);
  22851. }
  22852. if (renderingGroup) {
  22853. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22854. var step = _a[_i];
  22855. step.action(index);
  22856. }
  22857. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22858. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22859. var step = _c[_b];
  22860. step.action(index);
  22861. }
  22862. }
  22863. // Fire POSTTRANSPARENT stage
  22864. if (observable && info) {
  22865. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22866. observable.notifyObservers(info, renderingGroupMask);
  22867. }
  22868. }
  22869. };
  22870. RenderingManager.prototype.reset = function () {
  22871. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22872. var renderingGroup = this._renderingGroups[index];
  22873. if (renderingGroup) {
  22874. renderingGroup.prepare();
  22875. }
  22876. }
  22877. };
  22878. RenderingManager.prototype.dispose = function () {
  22879. this.freeRenderingGroups();
  22880. this._renderingGroups.length = 0;
  22881. };
  22882. /**
  22883. * Clear the info related to rendering groups preventing retention points during dispose.
  22884. */
  22885. RenderingManager.prototype.freeRenderingGroups = function () {
  22886. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22887. var renderingGroup = this._renderingGroups[index];
  22888. if (renderingGroup) {
  22889. renderingGroup.dispose();
  22890. }
  22891. }
  22892. };
  22893. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22894. if (this._renderingGroups[renderingGroupId] === undefined) {
  22895. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22896. }
  22897. };
  22898. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22899. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22900. this._prepareRenderingGroup(renderingGroupId);
  22901. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22902. };
  22903. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22904. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22905. this._prepareRenderingGroup(renderingGroupId);
  22906. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22907. };
  22908. /**
  22909. * @param subMesh The submesh to dispatch
  22910. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22911. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22912. */
  22913. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22914. if (mesh === undefined) {
  22915. mesh = subMesh.getMesh();
  22916. }
  22917. var renderingGroupId = mesh.renderingGroupId || 0;
  22918. this._prepareRenderingGroup(renderingGroupId);
  22919. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22920. };
  22921. /**
  22922. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22923. * This allowed control for front to back rendering or reversly depending of the special needs.
  22924. *
  22925. * @param renderingGroupId The rendering group id corresponding to its index
  22926. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22927. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22928. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22929. */
  22930. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22931. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22932. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22933. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22934. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22935. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22936. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22937. if (this._renderingGroups[renderingGroupId]) {
  22938. var group = this._renderingGroups[renderingGroupId];
  22939. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22940. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22941. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22942. }
  22943. };
  22944. /**
  22945. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22946. *
  22947. * @param renderingGroupId The rendering group id corresponding to its index
  22948. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22949. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22950. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22951. */
  22952. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22953. if (depth === void 0) { depth = true; }
  22954. if (stencil === void 0) { stencil = true; }
  22955. this._autoClearDepthStencil[renderingGroupId] = {
  22956. autoClear: autoClearDepthStencil,
  22957. depth: depth,
  22958. stencil: stencil
  22959. };
  22960. };
  22961. /**
  22962. * The max id used for rendering groups (not included)
  22963. */
  22964. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22965. /**
  22966. * The min id used for rendering groups (included)
  22967. */
  22968. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22969. /**
  22970. * Used to globally prevent autoclearing scenes.
  22971. */
  22972. RenderingManager.AUTOCLEAR = true;
  22973. return RenderingManager;
  22974. }());
  22975. BABYLON.RenderingManager = RenderingManager;
  22976. })(BABYLON || (BABYLON = {}));
  22977. //# sourceMappingURL=babylon.renderingManager.js.map
  22978. var BABYLON;
  22979. (function (BABYLON) {
  22980. var RenderingGroup = /** @class */ (function () {
  22981. /**
  22982. * Creates a new rendering group.
  22983. * @param index The rendering group index
  22984. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22985. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22986. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22987. */
  22988. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22989. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22990. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22991. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22992. this.index = index;
  22993. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22994. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22995. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22996. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22997. this._particleSystems = new BABYLON.SmartArray(256);
  22998. this._spriteManagers = new BABYLON.SmartArray(256);
  22999. this._edgesRenderers = new BABYLON.SmartArray(16);
  23000. this._scene = scene;
  23001. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23002. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23003. this.transparentSortCompareFn = transparentSortCompareFn;
  23004. }
  23005. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23006. /**
  23007. * Set the opaque sort comparison function.
  23008. * If null the sub meshes will be render in the order they were created
  23009. */
  23010. set: function (value) {
  23011. this._opaqueSortCompareFn = value;
  23012. if (value) {
  23013. this._renderOpaque = this.renderOpaqueSorted;
  23014. }
  23015. else {
  23016. this._renderOpaque = RenderingGroup.renderUnsorted;
  23017. }
  23018. },
  23019. enumerable: true,
  23020. configurable: true
  23021. });
  23022. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23023. /**
  23024. * Set the alpha test sort comparison function.
  23025. * If null the sub meshes will be render in the order they were created
  23026. */
  23027. set: function (value) {
  23028. this._alphaTestSortCompareFn = value;
  23029. if (value) {
  23030. this._renderAlphaTest = this.renderAlphaTestSorted;
  23031. }
  23032. else {
  23033. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23034. }
  23035. },
  23036. enumerable: true,
  23037. configurable: true
  23038. });
  23039. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23040. /**
  23041. * Set the transparent sort comparison function.
  23042. * If null the sub meshes will be render in the order they were created
  23043. */
  23044. set: function (value) {
  23045. if (value) {
  23046. this._transparentSortCompareFn = value;
  23047. }
  23048. else {
  23049. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23050. }
  23051. this._renderTransparent = this.renderTransparentSorted;
  23052. },
  23053. enumerable: true,
  23054. configurable: true
  23055. });
  23056. /**
  23057. * Render all the sub meshes contained in the group.
  23058. * @param customRenderFunction Used to override the default render behaviour of the group.
  23059. * @returns true if rendered some submeshes.
  23060. */
  23061. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23062. if (customRenderFunction) {
  23063. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23064. return;
  23065. }
  23066. var engine = this._scene.getEngine();
  23067. // Depth only
  23068. if (this._depthOnlySubMeshes.length !== 0) {
  23069. engine.setColorWrite(false);
  23070. this._renderAlphaTest(this._depthOnlySubMeshes);
  23071. engine.setColorWrite(true);
  23072. }
  23073. // Opaque
  23074. if (this._opaqueSubMeshes.length !== 0) {
  23075. this._renderOpaque(this._opaqueSubMeshes);
  23076. }
  23077. // Alpha test
  23078. if (this._alphaTestSubMeshes.length !== 0) {
  23079. this._renderAlphaTest(this._alphaTestSubMeshes);
  23080. }
  23081. var stencilState = engine.getStencilBuffer();
  23082. engine.setStencilBuffer(false);
  23083. // Sprites
  23084. if (renderSprites) {
  23085. this._renderSprites();
  23086. }
  23087. // Particles
  23088. if (renderParticles) {
  23089. this._renderParticles(activeMeshes);
  23090. }
  23091. if (this.onBeforeTransparentRendering) {
  23092. this.onBeforeTransparentRendering();
  23093. }
  23094. // Transparent
  23095. if (this._transparentSubMeshes.length !== 0) {
  23096. this._renderTransparent(this._transparentSubMeshes);
  23097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23098. }
  23099. // Set back stencil to false in case it changes before the edge renderer.
  23100. engine.setStencilBuffer(false);
  23101. // Edges
  23102. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23103. this._edgesRenderers.data[edgesRendererIndex].render();
  23104. }
  23105. // Restore Stencil state.
  23106. engine.setStencilBuffer(stencilState);
  23107. };
  23108. /**
  23109. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23110. * @param subMeshes The submeshes to render
  23111. */
  23112. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23113. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23114. };
  23115. /**
  23116. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23117. * @param subMeshes The submeshes to render
  23118. */
  23119. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23120. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23121. };
  23122. /**
  23123. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23124. * @param subMeshes The submeshes to render
  23125. */
  23126. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23127. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23128. };
  23129. /**
  23130. * Renders the submeshes in a specified order.
  23131. * @param subMeshes The submeshes to sort before render
  23132. * @param sortCompareFn The comparison function use to sort
  23133. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23134. * @param transparent Specifies to activate blending if true
  23135. */
  23136. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23137. var subIndex = 0;
  23138. var subMesh;
  23139. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23140. for (; subIndex < subMeshes.length; subIndex++) {
  23141. subMesh = subMeshes.data[subIndex];
  23142. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23143. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23144. }
  23145. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23146. if (sortCompareFn) {
  23147. sortedArray.sort(sortCompareFn);
  23148. }
  23149. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23150. subMesh = sortedArray[subIndex];
  23151. if (transparent) {
  23152. var material = subMesh.getMaterial();
  23153. if (material && material.needDepthPrePass) {
  23154. var engine = material.getScene().getEngine();
  23155. engine.setColorWrite(false);
  23156. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23157. subMesh.render(false);
  23158. engine.setColorWrite(true);
  23159. }
  23160. }
  23161. subMesh.render(transparent);
  23162. }
  23163. };
  23164. /**
  23165. * Renders the submeshes in the order they were dispatched (no sort applied).
  23166. * @param subMeshes The submeshes to render
  23167. */
  23168. RenderingGroup.renderUnsorted = function (subMeshes) {
  23169. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23170. var submesh = subMeshes.data[subIndex];
  23171. submesh.render(false);
  23172. }
  23173. };
  23174. /**
  23175. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23176. * are rendered back to front if in the same alpha index.
  23177. *
  23178. * @param a The first submesh
  23179. * @param b The second submesh
  23180. * @returns The result of the comparison
  23181. */
  23182. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23183. // Alpha index first
  23184. if (a._alphaIndex > b._alphaIndex) {
  23185. return 1;
  23186. }
  23187. if (a._alphaIndex < b._alphaIndex) {
  23188. return -1;
  23189. }
  23190. // Then distance to camera
  23191. return RenderingGroup.backToFrontSortCompare(a, b);
  23192. };
  23193. /**
  23194. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23195. * are rendered back to front.
  23196. *
  23197. * @param a The first submesh
  23198. * @param b The second submesh
  23199. * @returns The result of the comparison
  23200. */
  23201. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23202. // Then distance to camera
  23203. if (a._distanceToCamera < b._distanceToCamera) {
  23204. return 1;
  23205. }
  23206. if (a._distanceToCamera > b._distanceToCamera) {
  23207. return -1;
  23208. }
  23209. return 0;
  23210. };
  23211. /**
  23212. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23213. * are rendered front to back (prevent overdraw).
  23214. *
  23215. * @param a The first submesh
  23216. * @param b The second submesh
  23217. * @returns The result of the comparison
  23218. */
  23219. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23220. // Then distance to camera
  23221. if (a._distanceToCamera < b._distanceToCamera) {
  23222. return -1;
  23223. }
  23224. if (a._distanceToCamera > b._distanceToCamera) {
  23225. return 1;
  23226. }
  23227. return 0;
  23228. };
  23229. /**
  23230. * Resets the different lists of submeshes to prepare a new frame.
  23231. */
  23232. RenderingGroup.prototype.prepare = function () {
  23233. this._opaqueSubMeshes.reset();
  23234. this._transparentSubMeshes.reset();
  23235. this._alphaTestSubMeshes.reset();
  23236. this._depthOnlySubMeshes.reset();
  23237. this._particleSystems.reset();
  23238. this._spriteManagers.reset();
  23239. this._edgesRenderers.reset();
  23240. };
  23241. RenderingGroup.prototype.dispose = function () {
  23242. this._opaqueSubMeshes.dispose();
  23243. this._transparentSubMeshes.dispose();
  23244. this._alphaTestSubMeshes.dispose();
  23245. this._depthOnlySubMeshes.dispose();
  23246. this._particleSystems.dispose();
  23247. this._spriteManagers.dispose();
  23248. this._edgesRenderers.dispose();
  23249. };
  23250. /**
  23251. * Inserts the submesh in its correct queue depending on its material.
  23252. * @param subMesh The submesh to dispatch
  23253. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23254. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23255. */
  23256. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23257. // Get mesh and materials if not provided
  23258. if (mesh === undefined) {
  23259. mesh = subMesh.getMesh();
  23260. }
  23261. if (material === undefined) {
  23262. material = subMesh.getMaterial();
  23263. }
  23264. if (material === null || material === undefined) {
  23265. return;
  23266. }
  23267. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23268. this._transparentSubMeshes.push(subMesh);
  23269. }
  23270. else if (material.needAlphaTesting()) { // Alpha test
  23271. if (material.needDepthPrePass) {
  23272. this._depthOnlySubMeshes.push(subMesh);
  23273. }
  23274. this._alphaTestSubMeshes.push(subMesh);
  23275. }
  23276. else {
  23277. if (material.needDepthPrePass) {
  23278. this._depthOnlySubMeshes.push(subMesh);
  23279. }
  23280. this._opaqueSubMeshes.push(subMesh); // Opaque
  23281. }
  23282. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23283. this._edgesRenderers.push(mesh._edgesRenderer);
  23284. }
  23285. };
  23286. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23287. this._spriteManagers.push(spriteManager);
  23288. };
  23289. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23290. this._particleSystems.push(particleSystem);
  23291. };
  23292. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23293. if (this._particleSystems.length === 0) {
  23294. return;
  23295. }
  23296. // Particles
  23297. var activeCamera = this._scene.activeCamera;
  23298. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23299. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23300. var particleSystem = this._particleSystems.data[particleIndex];
  23301. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23302. continue;
  23303. }
  23304. var emitter = particleSystem.emitter;
  23305. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23306. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23307. }
  23308. }
  23309. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23310. };
  23311. RenderingGroup.prototype._renderSprites = function () {
  23312. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23313. return;
  23314. }
  23315. // Sprites
  23316. var activeCamera = this._scene.activeCamera;
  23317. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23318. for (var id = 0; id < this._spriteManagers.length; id++) {
  23319. var spriteManager = this._spriteManagers.data[id];
  23320. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23321. spriteManager.render();
  23322. }
  23323. }
  23324. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23325. };
  23326. return RenderingGroup;
  23327. }());
  23328. BABYLON.RenderingGroup = RenderingGroup;
  23329. })(BABYLON || (BABYLON = {}));
  23330. //# sourceMappingURL=babylon.renderingGroup.js.map
  23331. var BABYLON;
  23332. (function (BABYLON) {
  23333. /**
  23334. * Groups all the scene component constants in one place to ease maintenance.
  23335. * @hidden
  23336. */
  23337. var SceneComponentConstants = /** @class */ (function () {
  23338. function SceneComponentConstants() {
  23339. }
  23340. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23341. SceneComponentConstants.NAME_LAYER = "Layer";
  23342. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23343. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23344. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23345. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23346. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23347. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23348. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23349. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23350. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23351. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23352. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23353. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23354. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23355. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23356. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23357. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23358. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23359. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23360. return SceneComponentConstants;
  23361. }());
  23362. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23363. /**
  23364. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23365. * @hidden
  23366. */
  23367. var Stage = /** @class */ (function (_super) {
  23368. __extends(Stage, _super);
  23369. /**
  23370. * Hide ctor from the rest of the world.
  23371. * @param items The items to add.
  23372. */
  23373. function Stage(items) {
  23374. return _super.apply(this, items) || this;
  23375. }
  23376. /**
  23377. * Creates a new Stage.
  23378. * @returns A new instance of a Stage
  23379. */
  23380. Stage.Create = function () {
  23381. return Object.create(Stage.prototype);
  23382. };
  23383. /**
  23384. * Registers a step in an ordered way in the targeted stage.
  23385. * @param index Defines the position to register the step in
  23386. * @param component Defines the component attached to the step
  23387. * @param action Defines the action to launch during the step
  23388. */
  23389. Stage.prototype.registerStep = function (index, component, action) {
  23390. var i = 0;
  23391. var maxIndex = Number.MAX_VALUE;
  23392. for (; i < this.length && i < maxIndex; i++) {
  23393. var step = this[i];
  23394. maxIndex = step.index;
  23395. }
  23396. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23397. };
  23398. /**
  23399. * Clears all the steps from the stage.
  23400. */
  23401. Stage.prototype.clear = function () {
  23402. this.length = 0;
  23403. };
  23404. return Stage;
  23405. }(Array));
  23406. BABYLON.Stage = Stage;
  23407. })(BABYLON || (BABYLON = {}));
  23408. //# sourceMappingURL=babylon.sceneComponent.js.map
  23409. var BABYLON;
  23410. (function (BABYLON) {
  23411. /**
  23412. * Base class of the scene acting as a container for the different elements composing a scene.
  23413. * This class is dynamically extended by the different components of the scene increasing
  23414. * flexibility and reducing coupling
  23415. */
  23416. var AbstractScene = /** @class */ (function () {
  23417. function AbstractScene() {
  23418. /** All of the cameras added to this scene
  23419. * @see http://doc.babylonjs.com/babylon101/cameras
  23420. */
  23421. this.cameras = new Array();
  23422. /**
  23423. * All of the lights added to this scene
  23424. * @see http://doc.babylonjs.com/babylon101/lights
  23425. */
  23426. this.lights = new Array();
  23427. /**
  23428. * All of the (abstract) meshes added to this scene
  23429. */
  23430. this.meshes = new Array();
  23431. /**
  23432. * The list of skeletons added to the scene
  23433. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23434. */
  23435. this.skeletons = new Array();
  23436. /**
  23437. * All of the particle systems added to this scene
  23438. * @see http://doc.babylonjs.com/babylon101/particles
  23439. */
  23440. this.particleSystems = new Array();
  23441. /**
  23442. * Gets a list of Animations associated with the scene
  23443. */
  23444. this.animations = [];
  23445. /**
  23446. * All of the animation groups added to this scene
  23447. * @see http://doc.babylonjs.com/how_to/group
  23448. */
  23449. this.animationGroups = new Array();
  23450. /**
  23451. * All of the multi-materials added to this scene
  23452. * @see http://doc.babylonjs.com/how_to/multi_materials
  23453. */
  23454. this.multiMaterials = new Array();
  23455. /**
  23456. * All of the materials added to this scene
  23457. * @see http://doc.babylonjs.com/babylon101/materials
  23458. */
  23459. this.materials = new Array();
  23460. /**
  23461. * The list of morph target managers added to the scene
  23462. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23463. */
  23464. this.morphTargetManagers = new Array();
  23465. /**
  23466. * The list of geometries used in the scene.
  23467. */
  23468. this.geometries = new Array();
  23469. /**
  23470. * All of the tranform nodes added to this scene
  23471. * @see http://doc.babylonjs.com/how_to/transformnode
  23472. */
  23473. this.transformNodes = new Array();
  23474. /**
  23475. * ActionManagers available on the scene.
  23476. */
  23477. this.actionManagers = new Array();
  23478. /**
  23479. * Sounds to keep.
  23480. */
  23481. this.sounds = new Array();
  23482. /**
  23483. * Textures to keep.
  23484. */
  23485. this.textures = new Array();
  23486. }
  23487. /**
  23488. * Adds a parser in the list of available ones
  23489. * @param name Defines the name of the parser
  23490. * @param parser Defines the parser to add
  23491. */
  23492. AbstractScene.AddParser = function (name, parser) {
  23493. this._BabylonFileParsers[name] = parser;
  23494. };
  23495. /**
  23496. * Gets a general parser from the list of avaialble ones
  23497. * @param name Defines the name of the parser
  23498. * @returns the requested parser or null
  23499. */
  23500. AbstractScene.GetParser = function (name) {
  23501. if (this._BabylonFileParsers[name]) {
  23502. return this._BabylonFileParsers[name];
  23503. }
  23504. return null;
  23505. };
  23506. /**
  23507. * Adds n individual parser in the list of available ones
  23508. * @param name Defines the name of the parser
  23509. * @param parser Defines the parser to add
  23510. */
  23511. AbstractScene.AddIndividualParser = function (name, parser) {
  23512. this._IndividualBabylonFileParsers[name] = parser;
  23513. };
  23514. /**
  23515. * Gets an individual parser from the list of avaialble ones
  23516. * @param name Defines the name of the parser
  23517. * @returns the requested parser or null
  23518. */
  23519. AbstractScene.GetIndividualParser = function (name) {
  23520. if (this._IndividualBabylonFileParsers[name]) {
  23521. return this._IndividualBabylonFileParsers[name];
  23522. }
  23523. return null;
  23524. };
  23525. /**
  23526. * Parser json data and populate both a scene and its associated container object
  23527. * @param jsonData Defines the data to parse
  23528. * @param scene Defines the scene to parse the data for
  23529. * @param container Defines the container attached to the parsing sequence
  23530. * @param rootUrl Defines the root url of the data
  23531. */
  23532. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23533. for (var parserName in this._BabylonFileParsers) {
  23534. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23535. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23536. }
  23537. }
  23538. };
  23539. /**
  23540. * Stores the list of available parsers in the application.
  23541. */
  23542. AbstractScene._BabylonFileParsers = {};
  23543. /**
  23544. * Stores the list of available individual parsers in the application.
  23545. */
  23546. AbstractScene._IndividualBabylonFileParsers = {};
  23547. return AbstractScene;
  23548. }());
  23549. BABYLON.AbstractScene = AbstractScene;
  23550. })(BABYLON || (BABYLON = {}));
  23551. //# sourceMappingURL=babylon.abstractScene.js.map
  23552. var BABYLON;
  23553. (function (BABYLON) {
  23554. /** @hidden */
  23555. var ClickInfo = /** @class */ (function () {
  23556. function ClickInfo() {
  23557. this._singleClick = false;
  23558. this._doubleClick = false;
  23559. this._hasSwiped = false;
  23560. this._ignore = false;
  23561. }
  23562. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23563. get: function () {
  23564. return this._singleClick;
  23565. },
  23566. set: function (b) {
  23567. this._singleClick = b;
  23568. },
  23569. enumerable: true,
  23570. configurable: true
  23571. });
  23572. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23573. get: function () {
  23574. return this._doubleClick;
  23575. },
  23576. set: function (b) {
  23577. this._doubleClick = b;
  23578. },
  23579. enumerable: true,
  23580. configurable: true
  23581. });
  23582. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23583. get: function () {
  23584. return this._hasSwiped;
  23585. },
  23586. set: function (b) {
  23587. this._hasSwiped = b;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23593. get: function () {
  23594. return this._ignore;
  23595. },
  23596. set: function (b) {
  23597. this._ignore = b;
  23598. },
  23599. enumerable: true,
  23600. configurable: true
  23601. });
  23602. return ClickInfo;
  23603. }());
  23604. /**
  23605. * This class is used by the onRenderingGroupObservable
  23606. */
  23607. var RenderingGroupInfo = /** @class */ (function () {
  23608. function RenderingGroupInfo() {
  23609. }
  23610. /**
  23611. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23612. * This stage will be fired no matter what
  23613. */
  23614. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23615. /**
  23616. * Called before opaque object are rendered.
  23617. * This stage will be fired only if there's 3D Opaque content to render
  23618. */
  23619. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23620. /**
  23621. * Called after the opaque objects are rendered and before the transparent ones
  23622. * This stage will be fired only if there's 3D transparent content to render
  23623. */
  23624. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23625. /**
  23626. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23627. * This stage will be fired no matter what
  23628. */
  23629. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23630. return RenderingGroupInfo;
  23631. }());
  23632. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23633. /**
  23634. * Represents a scene to be rendered by the engine.
  23635. * @see http://doc.babylonjs.com/features/scene
  23636. */
  23637. var Scene = /** @class */ (function (_super) {
  23638. __extends(Scene, _super);
  23639. /**
  23640. * Creates a new Scene
  23641. * @param engine defines the engine to use to render this scene
  23642. */
  23643. function Scene(engine) {
  23644. var _this = _super.call(this) || this;
  23645. // Members
  23646. /**
  23647. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23648. */
  23649. _this.autoClear = true;
  23650. /**
  23651. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23652. */
  23653. _this.autoClearDepthAndStencil = true;
  23654. /**
  23655. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23656. */
  23657. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23658. /**
  23659. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23660. */
  23661. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23662. _this._forceWireframe = false;
  23663. _this._forcePointsCloud = false;
  23664. /**
  23665. * Gets or sets a boolean indicating if animations are enabled
  23666. */
  23667. _this.animationsEnabled = true;
  23668. _this._animationPropertiesOverride = null;
  23669. /**
  23670. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23671. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23672. */
  23673. _this.useConstantAnimationDeltaTime = false;
  23674. /**
  23675. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23676. * Please note that it requires to run a ray cast through the scene on every frame
  23677. */
  23678. _this.constantlyUpdateMeshUnderPointer = false;
  23679. /**
  23680. * Defines the HTML cursor to use when hovering over interactive elements
  23681. */
  23682. _this.hoverCursor = "pointer";
  23683. /**
  23684. * Defines the HTML default cursor to use (empty by default)
  23685. */
  23686. _this.defaultCursor = "";
  23687. /**
  23688. * This is used to call preventDefault() on pointer down
  23689. * in order to block unwanted artifacts like system double clicks
  23690. */
  23691. _this.preventDefaultOnPointerDown = true;
  23692. // Metadata
  23693. /**
  23694. * Gets or sets user defined metadata
  23695. */
  23696. _this.metadata = null;
  23697. /**
  23698. * Use this array to add regular expressions used to disable offline support for specific urls
  23699. */
  23700. _this.disableOfflineSupportExceptionRules = new Array();
  23701. /**
  23702. * An event triggered when the scene is disposed.
  23703. */
  23704. _this.onDisposeObservable = new BABYLON.Observable();
  23705. _this._onDisposeObserver = null;
  23706. /**
  23707. * An event triggered before rendering the scene (right after animations and physics)
  23708. */
  23709. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23710. _this._onBeforeRenderObserver = null;
  23711. /**
  23712. * An event triggered after rendering the scene
  23713. */
  23714. _this.onAfterRenderObservable = new BABYLON.Observable();
  23715. _this._onAfterRenderObserver = null;
  23716. /**
  23717. * An event triggered before animating the scene
  23718. */
  23719. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered after animations processing
  23722. */
  23723. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23724. /**
  23725. * An event triggered before draw calls are ready to be sent
  23726. */
  23727. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23728. /**
  23729. * An event triggered after draw calls have been sent
  23730. */
  23731. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23732. /**
  23733. * An event triggered when physic simulation is about to be run
  23734. */
  23735. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23736. /**
  23737. * An event triggered when physic simulation has been done
  23738. */
  23739. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when the scene is ready
  23742. */
  23743. _this.onReadyObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered before rendering a camera
  23746. */
  23747. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23748. _this._onBeforeCameraRenderObserver = null;
  23749. /**
  23750. * An event triggered after rendering a camera
  23751. */
  23752. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23753. _this._onAfterCameraRenderObserver = null;
  23754. /**
  23755. * An event triggered when active meshes evaluation is about to start
  23756. */
  23757. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23758. /**
  23759. * An event triggered when active meshes evaluation is done
  23760. */
  23761. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23762. /**
  23763. * An event triggered when particles rendering is about to start
  23764. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23765. */
  23766. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23767. /**
  23768. * An event triggered when particles rendering is done
  23769. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23770. */
  23771. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when sprites rendering is about to start
  23774. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23775. */
  23776. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23777. /**
  23778. * An event triggered when sprites rendering is done
  23779. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23780. */
  23781. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23782. /**
  23783. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23784. */
  23785. _this.onDataLoadedObservable = new BABYLON.Observable();
  23786. /**
  23787. * An event triggered when a camera is created
  23788. */
  23789. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23790. /**
  23791. * An event triggered when a camera is removed
  23792. */
  23793. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23794. /**
  23795. * An event triggered when a light is created
  23796. */
  23797. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23798. /**
  23799. * An event triggered when a light is removed
  23800. */
  23801. _this.onLightRemovedObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered when a geometry is created
  23804. */
  23805. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23806. /**
  23807. * An event triggered when a geometry is removed
  23808. */
  23809. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when a transform node is created
  23812. */
  23813. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered when a transform node is removed
  23816. */
  23817. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered when a mesh is created
  23820. */
  23821. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23822. /**
  23823. * An event triggered when a mesh is removed
  23824. */
  23825. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23826. /**
  23827. * An event triggered when render targets are about to be rendered
  23828. * Can happen multiple times per frame.
  23829. */
  23830. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23831. /**
  23832. * An event triggered when render targets were rendered.
  23833. * Can happen multiple times per frame.
  23834. */
  23835. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered before calculating deterministic simulation step
  23838. */
  23839. _this.onBeforeStepObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered after calculating deterministic simulation step
  23842. */
  23843. _this.onAfterStepObservable = new BABYLON.Observable();
  23844. /**
  23845. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23846. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23847. * 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)
  23848. */
  23849. _this.onRenderingGroupObservable = new BABYLON.Observable();
  23850. // Animations
  23851. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23852. /**
  23853. * 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).
  23854. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23855. */
  23856. _this.onPrePointerObservable = new BABYLON.Observable();
  23857. /**
  23858. * Observable event triggered each time an input event is received from the rendering canvas
  23859. */
  23860. _this.onPointerObservable = new BABYLON.Observable();
  23861. _this._meshPickProceed = false;
  23862. _this._currentPickResult = null;
  23863. _this._previousPickResult = null;
  23864. _this._totalPointersPressed = 0;
  23865. _this._doubleClickOccured = false;
  23866. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23867. _this.cameraToUseForPointers = null;
  23868. _this._pointerX = 0;
  23869. _this._pointerY = 0;
  23870. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23871. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23872. _this._startingPointerTime = 0;
  23873. _this._previousStartingPointerTime = 0;
  23874. _this._pointerCaptures = {};
  23875. // Deterministic lockstep
  23876. _this._timeAccumulator = 0;
  23877. _this._currentStepId = 0;
  23878. _this._currentInternalStep = 0;
  23879. // Keyboard
  23880. /**
  23881. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23882. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23883. */
  23884. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23885. /**
  23886. * Observable event triggered each time an keyboard event is received from the hosting window
  23887. */
  23888. _this.onKeyboardObservable = new BABYLON.Observable();
  23889. // Coordinates system
  23890. _this._useRightHandedSystem = false;
  23891. // Fog
  23892. _this._fogEnabled = true;
  23893. _this._fogMode = Scene.FOGMODE_NONE;
  23894. /**
  23895. * Gets or sets the fog color to use
  23896. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23897. */
  23898. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23899. /**
  23900. * Gets or sets the fog density to use
  23901. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23902. */
  23903. _this.fogDensity = 0.1;
  23904. /**
  23905. * Gets or sets the fog start distance to use
  23906. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23907. */
  23908. _this.fogStart = 0;
  23909. /**
  23910. * Gets or sets the fog end distance to use
  23911. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23912. */
  23913. _this.fogEnd = 1000.0;
  23914. // Lights
  23915. _this._shadowsEnabled = true;
  23916. _this._lightsEnabled = true;
  23917. /** All of the active cameras added to this scene. */
  23918. _this.activeCameras = new Array();
  23919. // Textures
  23920. _this._texturesEnabled = true;
  23921. // Particles
  23922. /**
  23923. * Gets or sets a boolean indicating if particles are enabled on this scene
  23924. */
  23925. _this.particlesEnabled = true;
  23926. // Sprites
  23927. /**
  23928. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23929. */
  23930. _this.spritesEnabled = true;
  23931. /**
  23932. * All of the sprite managers added to this scene
  23933. * @see http://doc.babylonjs.com/babylon101/sprites
  23934. */
  23935. _this.spriteManagers = new Array();
  23936. // Skeletons
  23937. _this._skeletonsEnabled = true;
  23938. // Lens flares
  23939. /**
  23940. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23941. */
  23942. _this.lensFlaresEnabled = true;
  23943. // Collisions
  23944. /**
  23945. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23946. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23947. */
  23948. _this.collisionsEnabled = true;
  23949. /**
  23950. * Defines the gravity applied to this scene (used only for collisions)
  23951. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23952. */
  23953. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23954. // Postprocesses
  23955. /**
  23956. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23957. */
  23958. _this.postProcessesEnabled = true;
  23959. /**
  23960. * The list of postprocesses added to the scene
  23961. */
  23962. _this.postProcesses = new Array();
  23963. // Customs render targets
  23964. /**
  23965. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23966. */
  23967. _this.renderTargetsEnabled = true;
  23968. /**
  23969. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23970. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23971. */
  23972. _this.dumpNextRenderTargets = false;
  23973. /**
  23974. * The list of user defined render targets added to the scene
  23975. */
  23976. _this.customRenderTargets = new Array();
  23977. /**
  23978. * Gets the list of meshes imported to the scene through SceneLoader
  23979. */
  23980. _this.importedMeshesFiles = new Array();
  23981. // Probes
  23982. /**
  23983. * Gets or sets a boolean indicating if probes are enabled on this scene
  23984. */
  23985. _this.probesEnabled = true;
  23986. /**
  23987. * The list of reflection probes added to the scene
  23988. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23989. */
  23990. _this.reflectionProbes = new Array();
  23991. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23992. // Procedural textures
  23993. /**
  23994. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23995. */
  23996. _this.proceduralTexturesEnabled = true;
  23997. /**
  23998. * The list of procedural textures added to the scene
  23999. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24000. */
  24001. _this.proceduralTextures = new Array();
  24002. /**
  24003. * The list of sound tracks added to the scene
  24004. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24005. */
  24006. _this.soundTracks = new Array();
  24007. _this._audioEnabled = true;
  24008. _this._headphone = false;
  24009. // Performance counters
  24010. _this._totalVertices = new BABYLON.PerfCounter();
  24011. /** @hidden */
  24012. _this._activeIndices = new BABYLON.PerfCounter();
  24013. /** @hidden */
  24014. _this._activeParticles = new BABYLON.PerfCounter();
  24015. /** @hidden */
  24016. _this._activeBones = new BABYLON.PerfCounter();
  24017. _this._animationTime = 0;
  24018. /**
  24019. * Gets or sets a general scale for animation speed
  24020. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24021. */
  24022. _this.animationTimeScale = 1;
  24023. _this._renderId = 0;
  24024. _this._executeWhenReadyTimeoutId = -1;
  24025. _this._intermediateRendering = false;
  24026. _this._viewUpdateFlag = -1;
  24027. _this._projectionUpdateFlag = -1;
  24028. _this._alternateViewUpdateFlag = -1;
  24029. _this._alternateProjectionUpdateFlag = -1;
  24030. /** @hidden */
  24031. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24032. _this._activeRequests = new Array();
  24033. _this._pendingData = new Array();
  24034. _this._isDisposed = false;
  24035. /**
  24036. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24037. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24038. */
  24039. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24040. _this._activeMeshes = new BABYLON.SmartArray(256);
  24041. _this._processedMaterials = new BABYLON.SmartArray(256);
  24042. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24043. /** @hidden */
  24044. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24045. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24046. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24047. /** @hidden */
  24048. _this._activeAnimatables = new Array();
  24049. _this._transformMatrix = BABYLON.Matrix.Zero();
  24050. _this._useAlternateCameraConfiguration = false;
  24051. _this._alternateRendering = false;
  24052. /**
  24053. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24054. * This is useful if there are more lights that the maximum simulteanous authorized
  24055. */
  24056. _this.requireLightSorting = false;
  24057. _this._depthRenderer = {};
  24058. /**
  24059. * Backing store of defined scene components.
  24060. */
  24061. _this._components = [];
  24062. /**
  24063. * Backing store of defined scene components.
  24064. */
  24065. _this._serializableComponents = [];
  24066. /**
  24067. * List of components to register on the next registration step.
  24068. */
  24069. _this._transientComponents = [];
  24070. /**
  24071. * Defines the actions happening before camera updates.
  24072. */
  24073. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24074. /**
  24075. * Defines the actions happening during the per mesh ready checks.
  24076. */
  24077. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24078. /**
  24079. * Defines the actions happening before evaluate active mesh checks.
  24080. */
  24081. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24082. /**
  24083. * Defines the actions happening during the evaluate sub mesh checks.
  24084. */
  24085. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24086. /**
  24087. * Defines the actions happening during the active mesh stage.
  24088. */
  24089. _this._activeMeshStage = BABYLON.Stage.Create();
  24090. /**
  24091. * Defines the actions happening during the per camera render target step.
  24092. */
  24093. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24094. /**
  24095. * Defines the actions happening just before the active camera is drawing.
  24096. */
  24097. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24098. /**
  24099. * Defines the actions happening just before a rendering group is drawing.
  24100. */
  24101. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24102. /**
  24103. * Defines the actions happening just after a rendering group has been drawn.
  24104. */
  24105. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24106. /**
  24107. * Defines the actions happening just after the active camera has been drawn.
  24108. */
  24109. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24110. _this._activeMeshesFrozen = false;
  24111. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24112. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24113. _this._engine.scenes.push(_this);
  24114. _this._uid = null;
  24115. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24116. if (BABYLON.PostProcessManager) {
  24117. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24118. }
  24119. if (BABYLON.OutlineRenderer) {
  24120. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24121. }
  24122. if (BABYLON.Tools.IsWindowObjectExist()) {
  24123. _this.attachControl();
  24124. }
  24125. //simplification queue
  24126. if (BABYLON.SimplificationQueue) {
  24127. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24128. }
  24129. //collision coordinator initialization. For now legacy per default.
  24130. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24131. // Uniform Buffer
  24132. _this._createUbo();
  24133. // Default Image processing definition
  24134. if (BABYLON.ImageProcessingConfiguration) {
  24135. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24136. }
  24137. return _this;
  24138. }
  24139. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24140. /** The fog is deactivated */
  24141. get: function () {
  24142. return Scene._FOGMODE_NONE;
  24143. },
  24144. enumerable: true,
  24145. configurable: true
  24146. });
  24147. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24148. /** The fog density is following an exponential function */
  24149. get: function () {
  24150. return Scene._FOGMODE_EXP;
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24156. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24157. get: function () {
  24158. return Scene._FOGMODE_EXP2;
  24159. },
  24160. enumerable: true,
  24161. configurable: true
  24162. });
  24163. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24164. /** The fog density is following a linear function. */
  24165. get: function () {
  24166. return Scene._FOGMODE_LINEAR;
  24167. },
  24168. enumerable: true,
  24169. configurable: true
  24170. });
  24171. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24172. /**
  24173. * Texture used in all pbr material as the reflection texture.
  24174. * As in the majority of the scene they are the same (exception for multi room and so on),
  24175. * this is easier to reference from here than from all the materials.
  24176. */
  24177. get: function () {
  24178. return this._environmentTexture;
  24179. },
  24180. /**
  24181. * Texture used in all pbr material as the reflection texture.
  24182. * As in the majority of the scene they are the same (exception for multi room and so on),
  24183. * this is easier to set here than in all the materials.
  24184. */
  24185. set: function (value) {
  24186. if (this._environmentTexture === value) {
  24187. return;
  24188. }
  24189. this._environmentTexture = value;
  24190. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24191. },
  24192. enumerable: true,
  24193. configurable: true
  24194. });
  24195. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24196. /**
  24197. * Default image processing configuration used either in the rendering
  24198. * Forward main pass or through the imageProcessingPostProcess if present.
  24199. * As in the majority of the scene they are the same (exception for multi camera),
  24200. * this is easier to reference from here than from all the materials and post process.
  24201. *
  24202. * No setter as we it is a shared configuration, you can set the values instead.
  24203. */
  24204. get: function () {
  24205. return this._imageProcessingConfiguration;
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24211. get: function () {
  24212. return this._forceWireframe;
  24213. },
  24214. /**
  24215. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24216. */
  24217. set: function (value) {
  24218. if (this._forceWireframe === value) {
  24219. return;
  24220. }
  24221. this._forceWireframe = value;
  24222. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24228. get: function () {
  24229. return this._forcePointsCloud;
  24230. },
  24231. /**
  24232. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24233. */
  24234. set: function (value) {
  24235. if (this._forcePointsCloud === value) {
  24236. return;
  24237. }
  24238. this._forcePointsCloud = value;
  24239. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24245. /**
  24246. * Gets or sets the animation properties override
  24247. */
  24248. get: function () {
  24249. return this._animationPropertiesOverride;
  24250. },
  24251. set: function (value) {
  24252. this._animationPropertiesOverride = value;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "onDispose", {
  24258. /** Sets a function to be executed when this scene is disposed. */
  24259. set: function (callback) {
  24260. if (this._onDisposeObserver) {
  24261. this.onDisposeObservable.remove(this._onDisposeObserver);
  24262. }
  24263. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24264. },
  24265. enumerable: true,
  24266. configurable: true
  24267. });
  24268. Object.defineProperty(Scene.prototype, "beforeRender", {
  24269. /** Sets a function to be executed before rendering this scene */
  24270. set: function (callback) {
  24271. if (this._onBeforeRenderObserver) {
  24272. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24273. }
  24274. if (callback) {
  24275. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24276. }
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. Object.defineProperty(Scene.prototype, "afterRender", {
  24282. /** Sets a function to be executed after rendering this scene */
  24283. set: function (callback) {
  24284. if (this._onAfterRenderObserver) {
  24285. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24286. }
  24287. if (callback) {
  24288. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24289. }
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24295. /** Sets a function to be executed before rendering a camera*/
  24296. set: function (callback) {
  24297. if (this._onBeforeCameraRenderObserver) {
  24298. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24299. }
  24300. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24306. /** Sets a function to be executed after rendering a camera*/
  24307. set: function (callback) {
  24308. if (this._onAfterCameraRenderObserver) {
  24309. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24310. }
  24311. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24317. /**
  24318. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24319. */
  24320. get: function () {
  24321. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24322. },
  24323. enumerable: true,
  24324. configurable: true
  24325. });
  24326. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24327. get: function () {
  24328. return this._useRightHandedSystem;
  24329. },
  24330. /**
  24331. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24332. */
  24333. set: function (value) {
  24334. if (this._useRightHandedSystem === value) {
  24335. return;
  24336. }
  24337. this._useRightHandedSystem = value;
  24338. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. /**
  24344. * Sets the step Id used by deterministic lock step
  24345. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24346. * @param newStepId defines the step Id
  24347. */
  24348. Scene.prototype.setStepId = function (newStepId) {
  24349. this._currentStepId = newStepId;
  24350. };
  24351. ;
  24352. /**
  24353. * Gets the step Id used by deterministic lock step
  24354. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24355. * @returns the step Id
  24356. */
  24357. Scene.prototype.getStepId = function () {
  24358. return this._currentStepId;
  24359. };
  24360. ;
  24361. /**
  24362. * Gets the internal step used by deterministic lock step
  24363. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24364. * @returns the internal step
  24365. */
  24366. Scene.prototype.getInternalStep = function () {
  24367. return this._currentInternalStep;
  24368. };
  24369. ;
  24370. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24371. get: function () {
  24372. return this._fogEnabled;
  24373. },
  24374. /**
  24375. * Gets or sets a boolean indicating if fog is enabled on this scene
  24376. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24377. */
  24378. set: function (value) {
  24379. if (this._fogEnabled === value) {
  24380. return;
  24381. }
  24382. this._fogEnabled = value;
  24383. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24384. },
  24385. enumerable: true,
  24386. configurable: true
  24387. });
  24388. Object.defineProperty(Scene.prototype, "fogMode", {
  24389. get: function () {
  24390. return this._fogMode;
  24391. },
  24392. /**
  24393. * Gets or sets the fog mode to use
  24394. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24395. */
  24396. set: function (value) {
  24397. if (this._fogMode === value) {
  24398. return;
  24399. }
  24400. this._fogMode = value;
  24401. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24407. get: function () {
  24408. return this._shadowsEnabled;
  24409. },
  24410. /**
  24411. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24412. */
  24413. set: function (value) {
  24414. if (this._shadowsEnabled === value) {
  24415. return;
  24416. }
  24417. this._shadowsEnabled = value;
  24418. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24424. get: function () {
  24425. return this._lightsEnabled;
  24426. },
  24427. /**
  24428. * Gets or sets a boolean indicating if lights are enabled on this scene
  24429. */
  24430. set: function (value) {
  24431. if (this._lightsEnabled === value) {
  24432. return;
  24433. }
  24434. this._lightsEnabled = value;
  24435. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24441. /** The default material used on meshes when no material is affected */
  24442. get: function () {
  24443. if (!this._defaultMaterial) {
  24444. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24445. }
  24446. return this._defaultMaterial;
  24447. },
  24448. /** The default material used on meshes when no material is affected */
  24449. set: function (value) {
  24450. this._defaultMaterial = value;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24456. get: function () {
  24457. return this._texturesEnabled;
  24458. },
  24459. /**
  24460. * Gets or sets a boolean indicating if textures are enabled on this scene
  24461. */
  24462. set: function (value) {
  24463. if (this._texturesEnabled === value) {
  24464. return;
  24465. }
  24466. this._texturesEnabled = value;
  24467. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24473. get: function () {
  24474. return this._skeletonsEnabled;
  24475. },
  24476. /**
  24477. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24478. */
  24479. set: function (value) {
  24480. if (this._skeletonsEnabled === value) {
  24481. return;
  24482. }
  24483. this._skeletonsEnabled = value;
  24484. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24490. /**
  24491. * Gets the postprocess render pipeline manager
  24492. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24493. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24494. */
  24495. get: function () {
  24496. if (!this._postProcessRenderPipelineManager) {
  24497. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24498. }
  24499. return this._postProcessRenderPipelineManager;
  24500. },
  24501. enumerable: true,
  24502. configurable: true
  24503. });
  24504. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24505. /**
  24506. * Gets the main soundtrack associated with the scene
  24507. */
  24508. get: function () {
  24509. if (!this._mainSoundTrack) {
  24510. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24511. }
  24512. return this._mainSoundTrack;
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24518. /** @hidden */
  24519. get: function () {
  24520. return this._alternateRendering;
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24526. /**
  24527. * Gets the list of frustum planes (built from the active camera)
  24528. */
  24529. get: function () {
  24530. return this._frustumPlanes;
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24536. /**
  24537. * Gets the current geometry buffer associated to the scene.
  24538. */
  24539. get: function () {
  24540. return this._geometryBufferRenderer;
  24541. },
  24542. /**
  24543. * Sets the current geometry buffer for the scene.
  24544. */
  24545. set: function (geometryBufferRenderer) {
  24546. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24547. this._geometryBufferRenderer = geometryBufferRenderer;
  24548. }
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. /**
  24554. * Registers the transient components if needed.
  24555. */
  24556. Scene.prototype._registerTransientComponents = function () {
  24557. // Register components that have been associated lately to the scene.
  24558. if (this._transientComponents.length > 0) {
  24559. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24560. var component = _a[_i];
  24561. component.register();
  24562. }
  24563. this._transientComponents = [];
  24564. }
  24565. };
  24566. /**
  24567. * Add a component to the scene.
  24568. * Note that the ccomponent could be registered on th next frame if this is called after
  24569. * the register component stage.
  24570. * @param component Defines the component to add to the scene
  24571. */
  24572. Scene.prototype._addComponent = function (component) {
  24573. this._components.push(component);
  24574. this._transientComponents.push(component);
  24575. var serializableComponent = component;
  24576. if (serializableComponent.addFromContainer) {
  24577. this._serializableComponents.push(serializableComponent);
  24578. }
  24579. };
  24580. /**
  24581. * Gets a component from the scene.
  24582. * @param name defines the name of the component to retrieve
  24583. * @returns the component or null if not present
  24584. */
  24585. Scene.prototype._getComponent = function (name) {
  24586. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24587. var component = _a[_i];
  24588. if (component.name === name) {
  24589. return component;
  24590. }
  24591. }
  24592. return null;
  24593. };
  24594. Object.defineProperty(Scene.prototype, "debugLayer", {
  24595. /**
  24596. * Gets the debug layer (aka Inspector) associated with the scene
  24597. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24598. */
  24599. get: function () {
  24600. if (!this._debugLayer) {
  24601. this._debugLayer = new BABYLON.DebugLayer(this);
  24602. }
  24603. return this._debugLayer;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24609. /**
  24610. * Gets a boolean indicating if collisions are processed on a web worker
  24611. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24612. */
  24613. get: function () {
  24614. return this._workerCollisions;
  24615. },
  24616. set: function (enabled) {
  24617. if (!BABYLON.CollisionCoordinatorLegacy) {
  24618. return;
  24619. }
  24620. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24621. this._workerCollisions = enabled;
  24622. if (this.collisionCoordinator) {
  24623. this.collisionCoordinator.destroy();
  24624. }
  24625. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24626. this.collisionCoordinator.init(this);
  24627. },
  24628. enumerable: true,
  24629. configurable: true
  24630. });
  24631. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24632. /**
  24633. * Gets the octree used to boost mesh selection (picking)
  24634. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24635. */
  24636. get: function () {
  24637. return this._selectionOctree;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24643. /**
  24644. * Gets the mesh that is currently under the pointer
  24645. */
  24646. get: function () {
  24647. return this._pointerOverMesh;
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "pointerX", {
  24653. /**
  24654. * Gets the current on-screen X position of the pointer
  24655. */
  24656. get: function () {
  24657. return this._pointerX;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "pointerY", {
  24663. /**
  24664. * Gets the current on-screen Y position of the pointer
  24665. */
  24666. get: function () {
  24667. return this._pointerY;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. /**
  24673. * Gets the cached material (ie. the latest rendered one)
  24674. * @returns the cached material
  24675. */
  24676. Scene.prototype.getCachedMaterial = function () {
  24677. return this._cachedMaterial;
  24678. };
  24679. /**
  24680. * Gets the cached effect (ie. the latest rendered one)
  24681. * @returns the cached effect
  24682. */
  24683. Scene.prototype.getCachedEffect = function () {
  24684. return this._cachedEffect;
  24685. };
  24686. /**
  24687. * Gets the cached visibility state (ie. the latest rendered one)
  24688. * @returns the cached visibility state
  24689. */
  24690. Scene.prototype.getCachedVisibility = function () {
  24691. return this._cachedVisibility;
  24692. };
  24693. /**
  24694. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24695. * @param material defines the current material
  24696. * @param effect defines the current effect
  24697. * @param visibility defines the current visibility state
  24698. * @returns true if one parameter is not cached
  24699. */
  24700. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24701. if (visibility === void 0) { visibility = 1; }
  24702. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24703. };
  24704. /**
  24705. * Gets the outline renderer associated with the scene
  24706. * @returns a OutlineRenderer
  24707. */
  24708. Scene.prototype.getOutlineRenderer = function () {
  24709. return this._outlineRenderer;
  24710. };
  24711. /**
  24712. * Gets the engine associated with the scene
  24713. * @returns an Engine
  24714. */
  24715. Scene.prototype.getEngine = function () {
  24716. return this._engine;
  24717. };
  24718. /**
  24719. * Gets the total number of vertices rendered per frame
  24720. * @returns the total number of vertices rendered per frame
  24721. */
  24722. Scene.prototype.getTotalVertices = function () {
  24723. return this._totalVertices.current;
  24724. };
  24725. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24726. /**
  24727. * Gets the performance counter for total vertices
  24728. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24729. */
  24730. get: function () {
  24731. return this._totalVertices;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. /**
  24737. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24738. * @returns the total number of active indices rendered per frame
  24739. */
  24740. Scene.prototype.getActiveIndices = function () {
  24741. return this._activeIndices.current;
  24742. };
  24743. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24744. /**
  24745. * Gets the performance counter for active indices
  24746. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24747. */
  24748. get: function () {
  24749. return this._activeIndices;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. /**
  24755. * Gets the total number of active particles rendered per frame
  24756. * @returns the total number of active particles rendered per frame
  24757. */
  24758. Scene.prototype.getActiveParticles = function () {
  24759. return this._activeParticles.current;
  24760. };
  24761. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24762. /**
  24763. * Gets the performance counter for active particles
  24764. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24765. */
  24766. get: function () {
  24767. return this._activeParticles;
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. /**
  24773. * Gets the total number of active bones rendered per frame
  24774. * @returns the total number of active bones rendered per frame
  24775. */
  24776. Scene.prototype.getActiveBones = function () {
  24777. return this._activeBones.current;
  24778. };
  24779. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24780. /**
  24781. * Gets the performance counter for active bones
  24782. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24783. */
  24784. get: function () {
  24785. return this._activeBones;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. /** @hidden */
  24791. Scene.prototype.getInterFramePerfCounter = function () {
  24792. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24793. return 0;
  24794. };
  24795. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24796. /** @hidden */
  24797. get: function () {
  24798. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24799. return null;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. /** @hidden */
  24805. Scene.prototype.getLastFrameDuration = function () {
  24806. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24807. return 0;
  24808. };
  24809. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24810. /** @hidden */
  24811. get: function () {
  24812. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24813. return null;
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. /** @hidden */
  24819. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24820. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24821. return 0;
  24822. };
  24823. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24824. /** @hidden */
  24825. get: function () {
  24826. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24827. return null;
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. /**
  24833. * Gets the array of active meshes
  24834. * @returns an array of AbstractMesh
  24835. */
  24836. Scene.prototype.getActiveMeshes = function () {
  24837. return this._activeMeshes;
  24838. };
  24839. /** @hidden */
  24840. Scene.prototype.getRenderTargetsDuration = function () {
  24841. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. /** @hidden */
  24845. Scene.prototype.getRenderDuration = function () {
  24846. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24847. return 0;
  24848. };
  24849. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24850. /** @hidden */
  24851. get: function () {
  24852. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24853. return null;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. /** @hidden */
  24859. Scene.prototype.getParticlesDuration = function () {
  24860. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24861. return 0;
  24862. };
  24863. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24864. /** @hidden */
  24865. get: function () {
  24866. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24867. return null;
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. /** @hidden */
  24873. Scene.prototype.getSpritesDuration = function () {
  24874. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24875. return 0;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24878. /** @hidden */
  24879. get: function () {
  24880. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24881. return null;
  24882. },
  24883. enumerable: true,
  24884. configurable: true
  24885. });
  24886. /**
  24887. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24888. * @returns a number
  24889. */
  24890. Scene.prototype.getAnimationRatio = function () {
  24891. return this._animationRatio;
  24892. };
  24893. /**
  24894. * Gets an unique Id for the current frame
  24895. * @returns a number
  24896. */
  24897. Scene.prototype.getRenderId = function () {
  24898. return this._renderId;
  24899. };
  24900. /** Call this function if you want to manually increment the render Id*/
  24901. Scene.prototype.incrementRenderId = function () {
  24902. this._renderId++;
  24903. };
  24904. Scene.prototype._updatePointerPosition = function (evt) {
  24905. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24906. if (!canvasRect) {
  24907. return;
  24908. }
  24909. this._pointerX = evt.clientX - canvasRect.left;
  24910. this._pointerY = evt.clientY - canvasRect.top;
  24911. this._unTranslatedPointerX = this._pointerX;
  24912. this._unTranslatedPointerY = this._pointerY;
  24913. };
  24914. Scene.prototype._createUbo = function () {
  24915. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24916. this._sceneUbo.addUniform("viewProjection", 16);
  24917. this._sceneUbo.addUniform("view", 16);
  24918. };
  24919. Scene.prototype._createAlternateUbo = function () {
  24920. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24921. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24922. this._alternateSceneUbo.addUniform("view", 16);
  24923. };
  24924. // Pointers handling
  24925. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24926. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24927. if (result) {
  24928. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24929. }
  24930. return result;
  24931. };
  24932. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24933. if (pointerInfo.pickInfo) {
  24934. if (!pointerInfo.pickInfo.ray) {
  24935. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24936. }
  24937. }
  24938. };
  24939. /**
  24940. * Use this method to simulate a pointer move on a mesh
  24941. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24942. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24943. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24944. * @returns the current scene
  24945. */
  24946. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24947. var evt = new PointerEvent("pointermove", pointerEventInit);
  24948. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24949. return this;
  24950. }
  24951. return this._processPointerMove(pickResult, evt);
  24952. };
  24953. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24954. var canvas = this._engine.getRenderingCanvas();
  24955. if (!canvas) {
  24956. return this;
  24957. }
  24958. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24959. this.setPointerOverSprite(null);
  24960. this.setPointerOverMesh(pickResult.pickedMesh);
  24961. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24962. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24963. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24964. }
  24965. else {
  24966. canvas.style.cursor = this.hoverCursor;
  24967. }
  24968. }
  24969. else {
  24970. canvas.style.cursor = this.defaultCursor;
  24971. }
  24972. }
  24973. else {
  24974. this.setPointerOverMesh(null);
  24975. // Sprites
  24976. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24977. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24978. this.setPointerOverSprite(pickResult.pickedSprite);
  24979. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24980. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24981. }
  24982. else {
  24983. canvas.style.cursor = this.hoverCursor;
  24984. }
  24985. }
  24986. else {
  24987. this.setPointerOverSprite(null);
  24988. // Restore pointer
  24989. canvas.style.cursor = this.defaultCursor;
  24990. }
  24991. }
  24992. if (pickResult) {
  24993. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24994. if (this.onPointerMove) {
  24995. this.onPointerMove(evt, pickResult, type);
  24996. }
  24997. if (this.onPointerObservable.hasObservers()) {
  24998. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24999. this._setRayOnPointerInfo(pi);
  25000. this.onPointerObservable.notifyObservers(pi, type);
  25001. }
  25002. }
  25003. return this;
  25004. };
  25005. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25006. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25007. if (pickResult) {
  25008. pi.ray = pickResult.ray;
  25009. }
  25010. this.onPrePointerObservable.notifyObservers(pi, type);
  25011. if (pi.skipOnPointerObservable) {
  25012. return true;
  25013. }
  25014. else {
  25015. return false;
  25016. }
  25017. };
  25018. /**
  25019. * Use this method to simulate a pointer down on a mesh
  25020. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25021. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25022. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25023. * @returns the current scene
  25024. */
  25025. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25026. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25027. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25028. return this;
  25029. }
  25030. return this._processPointerDown(pickResult, evt);
  25031. };
  25032. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25033. var _this = this;
  25034. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25035. this._pickedDownMesh = pickResult.pickedMesh;
  25036. var actionManager = pickResult.pickedMesh.actionManager;
  25037. if (actionManager) {
  25038. if (actionManager.hasPickTriggers) {
  25039. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25040. switch (evt.button) {
  25041. case 0:
  25042. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. break;
  25044. case 1:
  25045. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25046. break;
  25047. case 2:
  25048. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25049. break;
  25050. }
  25051. }
  25052. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25053. window.setTimeout(function () {
  25054. 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);
  25055. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25056. if (_this._totalPointersPressed !== 0 &&
  25057. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25058. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25059. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25060. _this._startingPointerTime = 0;
  25061. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25062. }
  25063. }
  25064. }, Scene.LongPressDelay);
  25065. }
  25066. }
  25067. }
  25068. if (pickResult) {
  25069. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25070. if (this.onPointerDown) {
  25071. this.onPointerDown(evt, pickResult, type);
  25072. }
  25073. if (this.onPointerObservable.hasObservers()) {
  25074. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25075. this._setRayOnPointerInfo(pi);
  25076. this.onPointerObservable.notifyObservers(pi, type);
  25077. }
  25078. }
  25079. return this;
  25080. };
  25081. /**
  25082. * Use this method to simulate a pointer up on a mesh
  25083. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25084. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25085. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25086. * @returns the current scene
  25087. */
  25088. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25089. var evt = new PointerEvent("pointerup", pointerEventInit);
  25090. var clickInfo = new ClickInfo();
  25091. clickInfo.singleClick = true;
  25092. clickInfo.ignore = true;
  25093. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25094. return this;
  25095. }
  25096. return this._processPointerUp(pickResult, evt, clickInfo);
  25097. };
  25098. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25099. if (pickResult && pickResult && pickResult.pickedMesh) {
  25100. this._pickedUpMesh = pickResult.pickedMesh;
  25101. if (this._pickedDownMesh === this._pickedUpMesh) {
  25102. if (this.onPointerPick) {
  25103. this.onPointerPick(evt, pickResult);
  25104. }
  25105. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25106. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25107. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25108. this._setRayOnPointerInfo(pi);
  25109. this.onPointerObservable.notifyObservers(pi, type_1);
  25110. }
  25111. }
  25112. if (pickResult.pickedMesh.actionManager) {
  25113. if (clickInfo.ignore) {
  25114. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25115. }
  25116. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25117. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25118. }
  25119. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25120. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25121. }
  25122. }
  25123. }
  25124. if (this._pickedDownMesh &&
  25125. this._pickedDownMesh.actionManager &&
  25126. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25127. this._pickedDownMesh !== this._pickedUpMesh) {
  25128. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25129. }
  25130. var type = BABYLON.PointerEventTypes.POINTERUP;
  25131. if (this.onPointerObservable.hasObservers()) {
  25132. if (!clickInfo.ignore) {
  25133. if (!clickInfo.hasSwiped) {
  25134. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25135. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25136. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25137. this._setRayOnPointerInfo(pi);
  25138. this.onPointerObservable.notifyObservers(pi, type_2);
  25139. }
  25140. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25141. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25142. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25143. this._setRayOnPointerInfo(pi);
  25144. this.onPointerObservable.notifyObservers(pi, type_3);
  25145. }
  25146. }
  25147. }
  25148. else {
  25149. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25150. this._setRayOnPointerInfo(pi);
  25151. this.onPointerObservable.notifyObservers(pi, type);
  25152. }
  25153. }
  25154. if (this.onPointerUp) {
  25155. this.onPointerUp(evt, pickResult, type);
  25156. }
  25157. return this;
  25158. };
  25159. /**
  25160. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25161. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25162. * @returns true if the pointer was captured
  25163. */
  25164. Scene.prototype.isPointerCaptured = function (pointerId) {
  25165. if (pointerId === void 0) { pointerId = 0; }
  25166. return this._pointerCaptures[pointerId];
  25167. };
  25168. /**
  25169. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25170. * @param attachUp defines if you want to attach events to pointerup
  25171. * @param attachDown defines if you want to attach events to pointerdown
  25172. * @param attachMove defines if you want to attach events to pointermove
  25173. */
  25174. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25175. var _this = this;
  25176. if (attachUp === void 0) { attachUp = true; }
  25177. if (attachDown === void 0) { attachDown = true; }
  25178. if (attachMove === void 0) { attachMove = true; }
  25179. this._initActionManager = function (act, clickInfo) {
  25180. if (!_this._meshPickProceed) {
  25181. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25182. _this._currentPickResult = pickResult;
  25183. if (pickResult) {
  25184. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25185. }
  25186. _this._meshPickProceed = true;
  25187. }
  25188. return act;
  25189. };
  25190. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25191. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25192. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25193. btn !== _this._previousButtonPressed) {
  25194. _this._doubleClickOccured = false;
  25195. clickInfo.singleClick = true;
  25196. clickInfo.ignore = false;
  25197. cb(clickInfo, _this._currentPickResult);
  25198. }
  25199. };
  25200. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25201. var clickInfo = new ClickInfo();
  25202. _this._currentPickResult = null;
  25203. var act = null;
  25204. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25205. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25206. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25207. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25208. act = _this._initActionManager(act, clickInfo);
  25209. if (act)
  25210. checkPicking = act.hasPickTriggers;
  25211. }
  25212. if (checkPicking) {
  25213. var btn = evt.button;
  25214. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25215. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25216. if (!clickInfo.hasSwiped) {
  25217. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25218. if (!checkSingleClickImmediately) {
  25219. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25220. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25221. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25222. act = _this._initActionManager(act, clickInfo);
  25223. if (act)
  25224. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25225. }
  25226. }
  25227. if (checkSingleClickImmediately) {
  25228. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25229. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25230. btn !== _this._previousButtonPressed) {
  25231. clickInfo.singleClick = true;
  25232. cb(clickInfo, _this._currentPickResult);
  25233. }
  25234. }
  25235. // at least one double click is required to be check and exclusive double click is enabled
  25236. else {
  25237. // wait that no double click has been raised during the double click delay
  25238. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25239. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25240. }
  25241. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25242. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25243. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25244. act = _this._initActionManager(act, clickInfo);
  25245. if (act)
  25246. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25247. }
  25248. if (checkDoubleClick) {
  25249. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25250. if (btn === _this._previousButtonPressed &&
  25251. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25252. !_this._doubleClickOccured) {
  25253. // pointer has not moved for 2 clicks, it's a double click
  25254. if (!clickInfo.hasSwiped &&
  25255. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25256. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25257. _this._previousStartingPointerTime = 0;
  25258. _this._doubleClickOccured = true;
  25259. clickInfo.doubleClick = true;
  25260. clickInfo.ignore = false;
  25261. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25262. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25263. }
  25264. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25265. cb(clickInfo, _this._currentPickResult);
  25266. }
  25267. // if the two successive clicks are too far, it's just two simple clicks
  25268. else {
  25269. _this._doubleClickOccured = false;
  25270. _this._previousStartingPointerTime = _this._startingPointerTime;
  25271. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25272. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25273. _this._previousButtonPressed = btn;
  25274. if (Scene.ExclusiveDoubleClickMode) {
  25275. if (_this._previousDelayedSimpleClickTimeout) {
  25276. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25277. }
  25278. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25279. cb(clickInfo, _this._previousPickResult);
  25280. }
  25281. else {
  25282. cb(clickInfo, _this._currentPickResult);
  25283. }
  25284. }
  25285. }
  25286. // just the first click of the double has been raised
  25287. else {
  25288. _this._doubleClickOccured = false;
  25289. _this._previousStartingPointerTime = _this._startingPointerTime;
  25290. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25291. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25292. _this._previousButtonPressed = btn;
  25293. }
  25294. }
  25295. }
  25296. }
  25297. clickInfo.ignore = true;
  25298. cb(clickInfo, _this._currentPickResult);
  25299. };
  25300. this._spritePredicate = function (sprite) {
  25301. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25302. };
  25303. this._onPointerMove = function (evt) {
  25304. _this._updatePointerPosition(evt);
  25305. // PreObservable support
  25306. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25307. return;
  25308. }
  25309. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25310. return;
  25311. }
  25312. if (!_this.pointerMovePredicate) {
  25313. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25314. }
  25315. // Meshes
  25316. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25317. _this._processPointerMove(pickResult, evt);
  25318. };
  25319. this._onPointerDown = function (evt) {
  25320. _this._totalPointersPressed++;
  25321. _this._pickedDownMesh = null;
  25322. _this._meshPickProceed = false;
  25323. _this._updatePointerPosition(evt);
  25324. if (_this.preventDefaultOnPointerDown && canvas) {
  25325. evt.preventDefault();
  25326. canvas.focus();
  25327. }
  25328. // PreObservable support
  25329. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25330. return;
  25331. }
  25332. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25333. return;
  25334. }
  25335. _this._pointerCaptures[evt.pointerId] = true;
  25336. _this._startingPointerPosition.x = _this._pointerX;
  25337. _this._startingPointerPosition.y = _this._pointerY;
  25338. _this._startingPointerTime = Date.now();
  25339. if (!_this.pointerDownPredicate) {
  25340. _this.pointerDownPredicate = function (mesh) {
  25341. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25342. };
  25343. }
  25344. // Meshes
  25345. _this._pickedDownMesh = null;
  25346. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25347. _this._processPointerDown(pickResult, evt);
  25348. // Sprites
  25349. _this._pickedDownSprite = null;
  25350. if (_this.spriteManagers.length > 0) {
  25351. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25352. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25353. if (pickResult.pickedSprite.actionManager) {
  25354. _this._pickedDownSprite = pickResult.pickedSprite;
  25355. switch (evt.button) {
  25356. case 0:
  25357. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25358. break;
  25359. case 1:
  25360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25361. break;
  25362. case 2:
  25363. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25364. break;
  25365. }
  25366. if (pickResult.pickedSprite.actionManager) {
  25367. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25368. }
  25369. }
  25370. }
  25371. }
  25372. };
  25373. this._onPointerUp = function (evt) {
  25374. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25375. return; // So we need to test it the pointer down was pressed before.
  25376. }
  25377. _this._totalPointersPressed--;
  25378. _this._pickedUpMesh = null;
  25379. _this._meshPickProceed = false;
  25380. _this._updatePointerPosition(evt);
  25381. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25382. // PreObservable support
  25383. if (_this.onPrePointerObservable.hasObservers()) {
  25384. if (!clickInfo.ignore) {
  25385. if (!clickInfo.hasSwiped) {
  25386. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25387. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. return;
  25389. }
  25390. }
  25391. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25392. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25393. return;
  25394. }
  25395. }
  25396. }
  25397. }
  25398. else {
  25399. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25400. return;
  25401. }
  25402. }
  25403. }
  25404. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25405. return;
  25406. }
  25407. _this._pointerCaptures[evt.pointerId] = false;
  25408. if (!_this.pointerUpPredicate) {
  25409. _this.pointerUpPredicate = function (mesh) {
  25410. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25411. };
  25412. }
  25413. // Meshes
  25414. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25415. _this._initActionManager(null, clickInfo);
  25416. }
  25417. if (!pickResult) {
  25418. pickResult = _this._currentPickResult;
  25419. }
  25420. _this._processPointerUp(pickResult, evt, clickInfo);
  25421. // Sprites
  25422. if (!clickInfo.ignore) {
  25423. if (_this.spriteManagers.length > 0) {
  25424. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25425. if (spritePickResult) {
  25426. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25427. if (spritePickResult.pickedSprite.actionManager) {
  25428. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25429. if (spritePickResult.pickedSprite.actionManager) {
  25430. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25431. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25432. }
  25433. }
  25434. }
  25435. }
  25436. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25437. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25438. }
  25439. }
  25440. }
  25441. }
  25442. _this._previousPickResult = _this._currentPickResult;
  25443. });
  25444. };
  25445. this._onKeyDown = function (evt) {
  25446. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25447. if (_this.onPreKeyboardObservable.hasObservers()) {
  25448. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25449. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25450. if (pi.skipOnPointerObservable) {
  25451. return;
  25452. }
  25453. }
  25454. if (_this.onKeyboardObservable.hasObservers()) {
  25455. var pi = new BABYLON.KeyboardInfo(type, evt);
  25456. _this.onKeyboardObservable.notifyObservers(pi, type);
  25457. }
  25458. if (_this.actionManager) {
  25459. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25460. }
  25461. };
  25462. this._onKeyUp = function (evt) {
  25463. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25464. if (_this.onPreKeyboardObservable.hasObservers()) {
  25465. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25466. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25467. if (pi.skipOnPointerObservable) {
  25468. return;
  25469. }
  25470. }
  25471. if (_this.onKeyboardObservable.hasObservers()) {
  25472. var pi = new BABYLON.KeyboardInfo(type, evt);
  25473. _this.onKeyboardObservable.notifyObservers(pi, type);
  25474. }
  25475. if (_this.actionManager) {
  25476. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25477. }
  25478. };
  25479. var engine = this.getEngine();
  25480. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25481. if (!canvas) {
  25482. return;
  25483. }
  25484. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25485. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25486. });
  25487. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25488. if (!canvas) {
  25489. return;
  25490. }
  25491. canvas.removeEventListener("keydown", _this._onKeyDown);
  25492. canvas.removeEventListener("keyup", _this._onKeyUp);
  25493. });
  25494. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25495. var canvas = this._engine.getRenderingCanvas();
  25496. if (!canvas) {
  25497. return;
  25498. }
  25499. if (attachMove) {
  25500. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25501. // Wheel
  25502. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25503. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25504. }
  25505. if (attachDown) {
  25506. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25507. }
  25508. if (attachUp) {
  25509. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25510. }
  25511. canvas.tabIndex = 1;
  25512. };
  25513. /** Detaches all event handlers*/
  25514. Scene.prototype.detachControl = function () {
  25515. var engine = this.getEngine();
  25516. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25517. var canvas = engine.getRenderingCanvas();
  25518. if (!canvas) {
  25519. return;
  25520. }
  25521. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25522. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25523. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25524. if (this._onCanvasBlurObserver) {
  25525. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25526. }
  25527. if (this._onCanvasFocusObserver) {
  25528. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25529. }
  25530. // Wheel
  25531. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25532. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25533. // Keyboard
  25534. canvas.removeEventListener("keydown", this._onKeyDown);
  25535. canvas.removeEventListener("keyup", this._onKeyUp);
  25536. // Observables
  25537. this.onKeyboardObservable.clear();
  25538. this.onPreKeyboardObservable.clear();
  25539. this.onPointerObservable.clear();
  25540. this.onPrePointerObservable.clear();
  25541. };
  25542. /**
  25543. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25544. * Delay loaded resources are not taking in account
  25545. * @return true if all required resources are ready
  25546. */
  25547. Scene.prototype.isReady = function () {
  25548. if (this._isDisposed) {
  25549. return false;
  25550. }
  25551. if (this._pendingData.length > 0) {
  25552. return false;
  25553. }
  25554. var index;
  25555. var engine = this.getEngine();
  25556. // Geometries
  25557. for (index = 0; index < this.geometries.length; index++) {
  25558. var geometry = this.geometries[index];
  25559. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25560. return false;
  25561. }
  25562. }
  25563. // Meshes
  25564. for (index = 0; index < this.meshes.length; index++) {
  25565. var mesh = this.meshes[index];
  25566. if (!mesh.isEnabled()) {
  25567. continue;
  25568. }
  25569. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25570. continue;
  25571. }
  25572. if (!mesh.isReady(true)) {
  25573. return false;
  25574. }
  25575. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25576. // Is Ready For Mesh
  25577. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25578. var step = _a[_i];
  25579. if (!step.action(mesh, hardwareInstancedRendering)) {
  25580. return false;
  25581. }
  25582. }
  25583. }
  25584. // Post-processes
  25585. if (this.activeCameras && this.activeCameras.length > 0) {
  25586. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25587. var camera = _c[_b];
  25588. if (!camera.isReady(true)) {
  25589. return false;
  25590. }
  25591. }
  25592. }
  25593. else if (this.activeCamera) {
  25594. if (!this.activeCamera.isReady(true)) {
  25595. return false;
  25596. }
  25597. }
  25598. // Particles
  25599. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25600. var particleSystem = _e[_d];
  25601. if (!particleSystem.isReady()) {
  25602. return false;
  25603. }
  25604. }
  25605. return true;
  25606. };
  25607. /** Resets all cached information relative to material (including effect and visibility) */
  25608. Scene.prototype.resetCachedMaterial = function () {
  25609. this._cachedMaterial = null;
  25610. this._cachedEffect = null;
  25611. this._cachedVisibility = null;
  25612. };
  25613. /**
  25614. * Registers a function to be called before every frame render
  25615. * @param func defines the function to register
  25616. */
  25617. Scene.prototype.registerBeforeRender = function (func) {
  25618. this.onBeforeRenderObservable.add(func);
  25619. };
  25620. /**
  25621. * Unregisters a function called before every frame render
  25622. * @param func defines the function to unregister
  25623. */
  25624. Scene.prototype.unregisterBeforeRender = function (func) {
  25625. this.onBeforeRenderObservable.removeCallback(func);
  25626. };
  25627. /**
  25628. * Registers a function to be called after every frame render
  25629. * @param func defines the function to register
  25630. */
  25631. Scene.prototype.registerAfterRender = function (func) {
  25632. this.onAfterRenderObservable.add(func);
  25633. };
  25634. /**
  25635. * Unregisters a function called after every frame render
  25636. * @param func defines the function to unregister
  25637. */
  25638. Scene.prototype.unregisterAfterRender = function (func) {
  25639. this.onAfterRenderObservable.removeCallback(func);
  25640. };
  25641. Scene.prototype._executeOnceBeforeRender = function (func) {
  25642. var _this = this;
  25643. var execFunc = function () {
  25644. func();
  25645. setTimeout(function () {
  25646. _this.unregisterBeforeRender(execFunc);
  25647. });
  25648. };
  25649. this.registerBeforeRender(execFunc);
  25650. };
  25651. /**
  25652. * The provided function will run before render once and will be disposed afterwards.
  25653. * A timeout delay can be provided so that the function will be executed in N ms.
  25654. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25655. * @param func The function to be executed.
  25656. * @param timeout optional delay in ms
  25657. */
  25658. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25659. var _this = this;
  25660. if (timeout !== undefined) {
  25661. setTimeout(function () {
  25662. _this._executeOnceBeforeRender(func);
  25663. }, timeout);
  25664. }
  25665. else {
  25666. this._executeOnceBeforeRender(func);
  25667. }
  25668. };
  25669. /** @hidden */
  25670. Scene.prototype._addPendingData = function (data) {
  25671. this._pendingData.push(data);
  25672. };
  25673. /** @hidden */
  25674. Scene.prototype._removePendingData = function (data) {
  25675. var wasLoading = this.isLoading;
  25676. var index = this._pendingData.indexOf(data);
  25677. if (index !== -1) {
  25678. this._pendingData.splice(index, 1);
  25679. }
  25680. if (wasLoading && !this.isLoading) {
  25681. this.onDataLoadedObservable.notifyObservers(this);
  25682. }
  25683. };
  25684. /**
  25685. * Returns the number of items waiting to be loaded
  25686. * @returns the number of items waiting to be loaded
  25687. */
  25688. Scene.prototype.getWaitingItemsCount = function () {
  25689. return this._pendingData.length;
  25690. };
  25691. Object.defineProperty(Scene.prototype, "isLoading", {
  25692. /**
  25693. * Returns a boolean indicating if the scene is still loading data
  25694. */
  25695. get: function () {
  25696. return this._pendingData.length > 0;
  25697. },
  25698. enumerable: true,
  25699. configurable: true
  25700. });
  25701. /**
  25702. * Registers a function to be executed when the scene is ready
  25703. * @param {Function} func - the function to be executed
  25704. */
  25705. Scene.prototype.executeWhenReady = function (func) {
  25706. var _this = this;
  25707. this.onReadyObservable.add(func);
  25708. if (this._executeWhenReadyTimeoutId !== -1) {
  25709. return;
  25710. }
  25711. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25712. _this._checkIsReady();
  25713. }, 150);
  25714. };
  25715. /**
  25716. * Returns a promise that resolves when the scene is ready
  25717. * @returns A promise that resolves when the scene is ready
  25718. */
  25719. Scene.prototype.whenReadyAsync = function () {
  25720. var _this = this;
  25721. return new Promise(function (resolve) {
  25722. _this.executeWhenReady(function () {
  25723. resolve();
  25724. });
  25725. });
  25726. };
  25727. /** @hidden */
  25728. Scene.prototype._checkIsReady = function () {
  25729. var _this = this;
  25730. this._registerTransientComponents();
  25731. if (this.isReady()) {
  25732. this.onReadyObservable.notifyObservers(this);
  25733. this.onReadyObservable.clear();
  25734. this._executeWhenReadyTimeoutId = -1;
  25735. return;
  25736. }
  25737. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25738. _this._checkIsReady();
  25739. }, 150);
  25740. };
  25741. // Animations
  25742. /**
  25743. * Will start the animation sequence of a given target
  25744. * @param target defines the target
  25745. * @param from defines from which frame should animation start
  25746. * @param to defines until which frame should animation run.
  25747. * @param weight defines the weight to apply to the animation (1.0 by default)
  25748. * @param loop defines if the animation loops
  25749. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25750. * @param onAnimationEnd defines the function to be executed when the animation ends
  25751. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25752. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25753. * @returns the animatable object created for this animation
  25754. */
  25755. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25756. if (weight === void 0) { weight = 1.0; }
  25757. if (speedRatio === void 0) { speedRatio = 1.0; }
  25758. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25759. returnedAnimatable.weight = weight;
  25760. return returnedAnimatable;
  25761. };
  25762. /**
  25763. * Will start the animation sequence of a given target
  25764. * @param target defines the target
  25765. * @param from defines from which frame should animation start
  25766. * @param to defines until which frame should animation run.
  25767. * @param loop defines if the animation loops
  25768. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25769. * @param onAnimationEnd defines the function to be executed when the animation ends
  25770. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25771. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25772. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25773. * @returns the animatable object created for this animation
  25774. */
  25775. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25776. if (speedRatio === void 0) { speedRatio = 1.0; }
  25777. if (stopCurrent === void 0) { stopCurrent = true; }
  25778. if (from > to && speedRatio > 0) {
  25779. speedRatio *= -1;
  25780. }
  25781. if (stopCurrent) {
  25782. this.stopAnimation(target, undefined, targetMask);
  25783. }
  25784. if (!animatable) {
  25785. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25786. }
  25787. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25788. // Local animations
  25789. if (target.animations && shouldRunTargetAnimations) {
  25790. animatable.appendAnimations(target, target.animations);
  25791. }
  25792. // Children animations
  25793. if (target.getAnimatables) {
  25794. var animatables = target.getAnimatables();
  25795. for (var index = 0; index < animatables.length; index++) {
  25796. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25797. }
  25798. }
  25799. animatable.reset();
  25800. return animatable;
  25801. };
  25802. /**
  25803. * Begin a new animation on a given node
  25804. * @param target defines the target where the animation will take place
  25805. * @param animations defines the list of animations to start
  25806. * @param from defines the initial value
  25807. * @param to defines the final value
  25808. * @param loop defines if you want animation to loop (off by default)
  25809. * @param speedRatio defines the speed ratio to apply to all animations
  25810. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25811. * @returns the list of created animatables
  25812. */
  25813. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25814. if (speedRatio === undefined) {
  25815. speedRatio = 1.0;
  25816. }
  25817. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25818. return animatable;
  25819. };
  25820. /**
  25821. * Begin a new animation on a given node and its hierarchy
  25822. * @param target defines the root node where the animation will take place
  25823. * @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.
  25824. * @param animations defines the list of animations to start
  25825. * @param from defines the initial value
  25826. * @param to defines the final value
  25827. * @param loop defines if you want animation to loop (off by default)
  25828. * @param speedRatio defines the speed ratio to apply to all animations
  25829. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25830. * @returns the list of animatables created for all nodes
  25831. */
  25832. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25833. var children = target.getDescendants(directDescendantsOnly);
  25834. var result = [];
  25835. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25836. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25837. var child = children_1[_i];
  25838. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25839. }
  25840. return result;
  25841. };
  25842. /**
  25843. * Gets the animatable associated with a specific target
  25844. * @param target defines the target of the animatable
  25845. * @returns the required animatable if found
  25846. */
  25847. Scene.prototype.getAnimatableByTarget = function (target) {
  25848. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25849. if (this._activeAnimatables[index].target === target) {
  25850. return this._activeAnimatables[index];
  25851. }
  25852. }
  25853. return null;
  25854. };
  25855. /**
  25856. * Gets all animatables associated with a given target
  25857. * @param target defines the target to look animatables for
  25858. * @returns an array of Animatables
  25859. */
  25860. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25861. var result = [];
  25862. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25863. if (this._activeAnimatables[index].target === target) {
  25864. result.push(this._activeAnimatables[index]);
  25865. }
  25866. }
  25867. return result;
  25868. };
  25869. Object.defineProperty(Scene.prototype, "animatables", {
  25870. /**
  25871. * Gets all animatable attached to the scene
  25872. */
  25873. get: function () {
  25874. return this._activeAnimatables;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. /**
  25880. * Will stop the animation of the given target
  25881. * @param target - the target
  25882. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25883. * @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)
  25884. */
  25885. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25886. var animatables = this.getAllAnimatablesByTarget(target);
  25887. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25888. var animatable = animatables_1[_i];
  25889. animatable.stop(animationName, targetMask);
  25890. }
  25891. };
  25892. /**
  25893. * Stops and removes all animations that have been applied to the scene
  25894. */
  25895. Scene.prototype.stopAllAnimations = function () {
  25896. if (this._activeAnimatables) {
  25897. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25898. this._activeAnimatables[i].stop();
  25899. }
  25900. this._activeAnimatables = [];
  25901. }
  25902. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25903. var group = _a[_i];
  25904. group.stop();
  25905. }
  25906. };
  25907. Scene.prototype._animate = function () {
  25908. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25909. return;
  25910. }
  25911. // Getting time
  25912. var now = BABYLON.Tools.Now;
  25913. if (!this._animationTimeLast) {
  25914. if (this._pendingData.length > 0) {
  25915. return;
  25916. }
  25917. this._animationTimeLast = now;
  25918. }
  25919. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25920. this._animationTime += deltaTime;
  25921. this._animationTimeLast = now;
  25922. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25923. this._activeAnimatables[index]._animate(this._animationTime);
  25924. }
  25925. // Late animation bindings
  25926. this._processLateAnimationBindings();
  25927. };
  25928. /** @hidden */
  25929. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25930. var target = runtimeAnimation.target;
  25931. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25932. if (!target._lateAnimationHolders) {
  25933. target._lateAnimationHolders = {};
  25934. }
  25935. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25936. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25937. totalWeight: 0,
  25938. animations: [],
  25939. originalValue: originalValue
  25940. };
  25941. }
  25942. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25943. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25944. };
  25945. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25946. var normalizer = 1.0;
  25947. var finalPosition = BABYLON.Tmp.Vector3[0];
  25948. var finalScaling = BABYLON.Tmp.Vector3[1];
  25949. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25950. var startIndex = 0;
  25951. var originalAnimation = holder.animations[0];
  25952. var originalValue = holder.originalValue;
  25953. var scale = 1;
  25954. if (holder.totalWeight < 1.0) {
  25955. // We need to mix the original value in
  25956. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25957. scale = 1.0 - holder.totalWeight;
  25958. }
  25959. else {
  25960. startIndex = 1;
  25961. // We need to normalize the weights
  25962. normalizer = holder.totalWeight;
  25963. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25964. scale = originalAnimation.weight / normalizer;
  25965. if (scale == 1) {
  25966. return originalAnimation.currentValue;
  25967. }
  25968. }
  25969. finalScaling.scaleInPlace(scale);
  25970. finalPosition.scaleInPlace(scale);
  25971. finalQuaternion.scaleInPlace(scale);
  25972. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25973. var runtimeAnimation = holder.animations[animIndex];
  25974. var scale = runtimeAnimation.weight / normalizer;
  25975. var currentPosition = BABYLON.Tmp.Vector3[2];
  25976. var currentScaling = BABYLON.Tmp.Vector3[3];
  25977. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25978. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25979. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25980. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25981. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25982. }
  25983. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25984. return originalAnimation._workValue;
  25985. };
  25986. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25987. var originalAnimation = holder.animations[0];
  25988. var originalValue = holder.originalValue;
  25989. if (holder.animations.length === 1) {
  25990. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25991. }
  25992. var normalizer = 1.0;
  25993. var quaternions;
  25994. var weights;
  25995. if (holder.totalWeight < 1.0) {
  25996. var scale = 1.0 - holder.totalWeight;
  25997. quaternions = [];
  25998. weights = [];
  25999. quaternions.push(originalValue);
  26000. weights.push(scale);
  26001. }
  26002. else {
  26003. if (holder.animations.length === 2) { // Slerp as soon as we can
  26004. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26005. }
  26006. quaternions = [];
  26007. weights = [];
  26008. normalizer = holder.totalWeight;
  26009. }
  26010. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26011. var runtimeAnimation = holder.animations[animIndex];
  26012. quaternions.push(runtimeAnimation.currentValue);
  26013. weights.push(runtimeAnimation.weight / normalizer);
  26014. }
  26015. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26016. var cumulativeAmount = 0;
  26017. var cumulativeQuaternion = null;
  26018. for (var index = 0; index < quaternions.length;) {
  26019. if (!cumulativeQuaternion) {
  26020. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26021. cumulativeAmount = weights[index] + weights[index + 1];
  26022. index += 2;
  26023. continue;
  26024. }
  26025. cumulativeAmount += weights[index];
  26026. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26027. index++;
  26028. }
  26029. return cumulativeQuaternion;
  26030. };
  26031. Scene.prototype._processLateAnimationBindings = function () {
  26032. if (!this._registeredForLateAnimationBindings.length) {
  26033. return;
  26034. }
  26035. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26036. var target = this._registeredForLateAnimationBindings.data[index];
  26037. for (var path in target._lateAnimationHolders) {
  26038. var holder = target._lateAnimationHolders[path];
  26039. var originalAnimation = holder.animations[0];
  26040. var originalValue = holder.originalValue;
  26041. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26042. var finalValue = void 0;
  26043. if (matrixDecomposeMode) {
  26044. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26045. }
  26046. else {
  26047. var quaternionMode = originalValue.w !== undefined;
  26048. if (quaternionMode) {
  26049. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26050. }
  26051. else {
  26052. var startIndex = 0;
  26053. var normalizer = 1.0;
  26054. if (holder.totalWeight < 1.0) {
  26055. // We need to mix the original value in
  26056. if (originalValue.scale) {
  26057. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26058. }
  26059. else {
  26060. finalValue = originalValue * (1.0 - holder.totalWeight);
  26061. }
  26062. }
  26063. else {
  26064. // We need to normalize the weights
  26065. normalizer = holder.totalWeight;
  26066. var scale_1 = originalAnimation.weight / normalizer;
  26067. if (scale_1 !== 1) {
  26068. if (originalAnimation.currentValue.scale) {
  26069. finalValue = originalAnimation.currentValue.scale(scale_1);
  26070. }
  26071. else {
  26072. finalValue = originalAnimation.currentValue * scale_1;
  26073. }
  26074. }
  26075. else {
  26076. finalValue = originalAnimation.currentValue;
  26077. }
  26078. startIndex = 1;
  26079. }
  26080. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26081. var runtimeAnimation = holder.animations[animIndex];
  26082. var scale = runtimeAnimation.weight / normalizer;
  26083. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26084. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26085. }
  26086. else {
  26087. finalValue += runtimeAnimation.currentValue * scale;
  26088. }
  26089. }
  26090. }
  26091. }
  26092. target[path] = finalValue;
  26093. }
  26094. target._lateAnimationHolders = {};
  26095. }
  26096. this._registeredForLateAnimationBindings.reset();
  26097. };
  26098. // Matrix
  26099. /** @hidden */
  26100. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26101. this._useAlternateCameraConfiguration = active;
  26102. };
  26103. /**
  26104. * Gets the current view matrix
  26105. * @returns a Matrix
  26106. */
  26107. Scene.prototype.getViewMatrix = function () {
  26108. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26109. };
  26110. /**
  26111. * Gets the current projection matrix
  26112. * @returns a Matrix
  26113. */
  26114. Scene.prototype.getProjectionMatrix = function () {
  26115. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26116. };
  26117. /**
  26118. * Gets the current transform matrix
  26119. * @returns a Matrix made of View * Projection
  26120. */
  26121. Scene.prototype.getTransformMatrix = function () {
  26122. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26123. };
  26124. /**
  26125. * Sets the current transform matrix
  26126. * @param view defines the View matrix to use
  26127. * @param projection defines the Projection matrix to use
  26128. */
  26129. Scene.prototype.setTransformMatrix = function (view, projection) {
  26130. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26131. return;
  26132. }
  26133. this._viewUpdateFlag = view.updateFlag;
  26134. this._projectionUpdateFlag = projection.updateFlag;
  26135. this._viewMatrix = view;
  26136. this._projectionMatrix = projection;
  26137. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26138. // Update frustum
  26139. if (!this._frustumPlanes) {
  26140. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26141. }
  26142. else {
  26143. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26144. }
  26145. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26146. var otherCamera = this.activeCamera._alternateCamera;
  26147. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26148. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26149. }
  26150. if (this._sceneUbo.useUbo) {
  26151. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26152. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26153. this._sceneUbo.update();
  26154. }
  26155. };
  26156. /** @hidden */
  26157. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26158. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26159. return;
  26160. }
  26161. this._alternateViewUpdateFlag = view.updateFlag;
  26162. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26163. this._alternateViewMatrix = view;
  26164. this._alternateProjectionMatrix = projection;
  26165. if (!this._alternateTransformMatrix) {
  26166. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26167. }
  26168. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26169. if (!this._alternateSceneUbo) {
  26170. this._createAlternateUbo();
  26171. }
  26172. if (this._alternateSceneUbo.useUbo) {
  26173. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26174. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26175. this._alternateSceneUbo.update();
  26176. }
  26177. };
  26178. /**
  26179. * Gets the uniform buffer used to store scene data
  26180. * @returns a UniformBuffer
  26181. */
  26182. Scene.prototype.getSceneUniformBuffer = function () {
  26183. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26184. };
  26185. /**
  26186. * Gets an unique (relatively to the current scene) Id
  26187. * @returns an unique number for the scene
  26188. */
  26189. Scene.prototype.getUniqueId = function () {
  26190. var result = Scene._uniqueIdCounter;
  26191. Scene._uniqueIdCounter++;
  26192. return result;
  26193. };
  26194. /**
  26195. * Add a mesh to the list of scene's meshes
  26196. * @param newMesh defines the mesh to add
  26197. * @param recursive if all child meshes should also be added to the scene
  26198. */
  26199. Scene.prototype.addMesh = function (newMesh, recursive) {
  26200. var _this = this;
  26201. if (recursive === void 0) { recursive = false; }
  26202. this.meshes.push(newMesh);
  26203. //notify the collision coordinator
  26204. if (this.collisionCoordinator) {
  26205. this.collisionCoordinator.onMeshAdded(newMesh);
  26206. }
  26207. newMesh._resyncLightSources();
  26208. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26209. if (recursive) {
  26210. newMesh.getChildMeshes().forEach(function (m) {
  26211. _this.addMesh(m);
  26212. });
  26213. }
  26214. };
  26215. /**
  26216. * Remove a mesh for the list of scene's meshes
  26217. * @param toRemove defines the mesh to remove
  26218. * @param recursive if all child meshes should also be removed from the scene
  26219. * @returns the index where the mesh was in the mesh list
  26220. */
  26221. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26222. var _this = this;
  26223. if (recursive === void 0) { recursive = false; }
  26224. var index = this.meshes.indexOf(toRemove);
  26225. if (index !== -1) {
  26226. // Remove from the scene if mesh found
  26227. this.meshes.splice(index, 1);
  26228. }
  26229. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26230. if (recursive) {
  26231. toRemove.getChildMeshes().forEach(function (m) {
  26232. _this.removeMesh(m);
  26233. });
  26234. }
  26235. return index;
  26236. };
  26237. /**
  26238. * Add a transform node to the list of scene's transform nodes
  26239. * @param newTransformNode defines the transform node to add
  26240. */
  26241. Scene.prototype.addTransformNode = function (newTransformNode) {
  26242. this.transformNodes.push(newTransformNode);
  26243. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26244. };
  26245. /**
  26246. * Remove a transform node for the list of scene's transform nodes
  26247. * @param toRemove defines the transform node to remove
  26248. * @returns the index where the transform node was in the transform node list
  26249. */
  26250. Scene.prototype.removeTransformNode = function (toRemove) {
  26251. var index = this.transformNodes.indexOf(toRemove);
  26252. if (index !== -1) {
  26253. // Remove from the scene if found
  26254. this.transformNodes.splice(index, 1);
  26255. }
  26256. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26257. return index;
  26258. };
  26259. /**
  26260. * Remove a skeleton for the list of scene's skeletons
  26261. * @param toRemove defines the skeleton to remove
  26262. * @returns the index where the skeleton was in the skeleton list
  26263. */
  26264. Scene.prototype.removeSkeleton = function (toRemove) {
  26265. var index = this.skeletons.indexOf(toRemove);
  26266. if (index !== -1) {
  26267. // Remove from the scene if found
  26268. this.skeletons.splice(index, 1);
  26269. }
  26270. return index;
  26271. };
  26272. /**
  26273. * Remove a morph target for the list of scene's morph targets
  26274. * @param toRemove defines the morph target to remove
  26275. * @returns the index where the morph target was in the morph target list
  26276. */
  26277. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26278. var index = this.morphTargetManagers.indexOf(toRemove);
  26279. if (index !== -1) {
  26280. // Remove from the scene if found
  26281. this.morphTargetManagers.splice(index, 1);
  26282. }
  26283. return index;
  26284. };
  26285. /**
  26286. * Remove a light for the list of scene's lights
  26287. * @param toRemove defines the light to remove
  26288. * @returns the index where the light was in the light list
  26289. */
  26290. Scene.prototype.removeLight = function (toRemove) {
  26291. var index = this.lights.indexOf(toRemove);
  26292. if (index !== -1) {
  26293. // Remove from meshes
  26294. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26295. var mesh = _a[_i];
  26296. mesh._removeLightSource(toRemove);
  26297. }
  26298. // Remove from the scene if mesh found
  26299. this.lights.splice(index, 1);
  26300. this.sortLightsByPriority();
  26301. }
  26302. this.onLightRemovedObservable.notifyObservers(toRemove);
  26303. return index;
  26304. };
  26305. /**
  26306. * Remove a camera for the list of scene's cameras
  26307. * @param toRemove defines the camera to remove
  26308. * @returns the index where the camera was in the camera list
  26309. */
  26310. Scene.prototype.removeCamera = function (toRemove) {
  26311. var index = this.cameras.indexOf(toRemove);
  26312. if (index !== -1) {
  26313. // Remove from the scene if mesh found
  26314. this.cameras.splice(index, 1);
  26315. }
  26316. // Remove from activeCameras
  26317. var index2 = this.activeCameras.indexOf(toRemove);
  26318. if (index2 !== -1) {
  26319. // Remove from the scene if mesh found
  26320. this.activeCameras.splice(index2, 1);
  26321. }
  26322. // Reset the activeCamera
  26323. if (this.activeCamera === toRemove) {
  26324. if (this.cameras.length > 0) {
  26325. this.activeCamera = this.cameras[0];
  26326. }
  26327. else {
  26328. this.activeCamera = null;
  26329. }
  26330. }
  26331. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26332. return index;
  26333. };
  26334. /**
  26335. * Remove a particle system for the list of scene's particle systems
  26336. * @param toRemove defines the particle system to remove
  26337. * @returns the index where the particle system was in the particle system list
  26338. */
  26339. Scene.prototype.removeParticleSystem = function (toRemove) {
  26340. var index = this.particleSystems.indexOf(toRemove);
  26341. if (index !== -1) {
  26342. this.particleSystems.splice(index, 1);
  26343. }
  26344. return index;
  26345. };
  26346. /**
  26347. * Remove a animation for the list of scene's animations
  26348. * @param toRemove defines the animation to remove
  26349. * @returns the index where the animation was in the animation list
  26350. */
  26351. Scene.prototype.removeAnimation = function (toRemove) {
  26352. var index = this.animations.indexOf(toRemove);
  26353. if (index !== -1) {
  26354. this.animations.splice(index, 1);
  26355. }
  26356. return index;
  26357. };
  26358. /**
  26359. * Removes the given animation group from this scene.
  26360. * @param toRemove The animation group to remove
  26361. * @returns The index of the removed animation group
  26362. */
  26363. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26364. var index = this.animationGroups.indexOf(toRemove);
  26365. if (index !== -1) {
  26366. this.animationGroups.splice(index, 1);
  26367. }
  26368. return index;
  26369. };
  26370. /**
  26371. * Removes the given multi-material from this scene.
  26372. * @param toRemove The multi-material to remove
  26373. * @returns The index of the removed multi-material
  26374. */
  26375. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26376. var index = this.multiMaterials.indexOf(toRemove);
  26377. if (index !== -1) {
  26378. this.multiMaterials.splice(index, 1);
  26379. }
  26380. return index;
  26381. };
  26382. /**
  26383. * Removes the given material from this scene.
  26384. * @param toRemove The material to remove
  26385. * @returns The index of the removed material
  26386. */
  26387. Scene.prototype.removeMaterial = function (toRemove) {
  26388. var index = this.materials.indexOf(toRemove);
  26389. if (index !== -1) {
  26390. this.materials.splice(index, 1);
  26391. }
  26392. return index;
  26393. };
  26394. /**
  26395. * Removes the given action manager from this scene.
  26396. * @param toRemove The action manager to remove
  26397. * @returns The index of the removed action manager
  26398. */
  26399. Scene.prototype.removeActionManager = function (toRemove) {
  26400. var index = this.actionManagers.indexOf(toRemove);
  26401. if (index !== -1) {
  26402. this.actionManagers.splice(index, 1);
  26403. }
  26404. return index;
  26405. };
  26406. /**
  26407. * Removes the given texture from this scene.
  26408. * @param toRemove The texture to remove
  26409. * @returns The index of the removed texture
  26410. */
  26411. Scene.prototype.removeTexture = function (toRemove) {
  26412. var index = this.textures.indexOf(toRemove);
  26413. if (index !== -1) {
  26414. this.textures.splice(index, 1);
  26415. }
  26416. return index;
  26417. };
  26418. /**
  26419. * Adds the given light to this scene
  26420. * @param newLight The light to add
  26421. */
  26422. Scene.prototype.addLight = function (newLight) {
  26423. this.lights.push(newLight);
  26424. this.sortLightsByPriority();
  26425. // Add light to all meshes (To support if the light is removed and then readded)
  26426. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26427. var mesh = _a[_i];
  26428. if (mesh._lightSources.indexOf(newLight) === -1) {
  26429. mesh._lightSources.push(newLight);
  26430. mesh._resyncLightSources();
  26431. }
  26432. }
  26433. this.onNewLightAddedObservable.notifyObservers(newLight);
  26434. };
  26435. /**
  26436. * Sorts the list list based on light priorities
  26437. */
  26438. Scene.prototype.sortLightsByPriority = function () {
  26439. if (this.requireLightSorting) {
  26440. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26441. }
  26442. };
  26443. /**
  26444. * Adds the given camera to this scene
  26445. * @param newCamera The camera to add
  26446. */
  26447. Scene.prototype.addCamera = function (newCamera) {
  26448. this.cameras.push(newCamera);
  26449. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26450. };
  26451. /**
  26452. * Adds the given skeleton to this scene
  26453. * @param newSkeleton The skeleton to add
  26454. */
  26455. Scene.prototype.addSkeleton = function (newSkeleton) {
  26456. this.skeletons.push(newSkeleton);
  26457. };
  26458. /**
  26459. * Adds the given particle system to this scene
  26460. * @param newParticleSystem The particle system to add
  26461. */
  26462. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26463. this.particleSystems.push(newParticleSystem);
  26464. };
  26465. /**
  26466. * Adds the given animation to this scene
  26467. * @param newAnimation The animation to add
  26468. */
  26469. Scene.prototype.addAnimation = function (newAnimation) {
  26470. this.animations.push(newAnimation);
  26471. };
  26472. /**
  26473. * Adds the given animation group to this scene.
  26474. * @param newAnimationGroup The animation group to add
  26475. */
  26476. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26477. this.animationGroups.push(newAnimationGroup);
  26478. };
  26479. /**
  26480. * Adds the given multi-material to this scene
  26481. * @param newMultiMaterial The multi-material to add
  26482. */
  26483. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26484. this.multiMaterials.push(newMultiMaterial);
  26485. };
  26486. /**
  26487. * Adds the given material to this scene
  26488. * @param newMaterial The material to add
  26489. */
  26490. Scene.prototype.addMaterial = function (newMaterial) {
  26491. this.materials.push(newMaterial);
  26492. };
  26493. /**
  26494. * Adds the given morph target to this scene
  26495. * @param newMorphTargetManager The morph target to add
  26496. */
  26497. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26498. this.morphTargetManagers.push(newMorphTargetManager);
  26499. };
  26500. /**
  26501. * Adds the given geometry to this scene
  26502. * @param newGeometry The geometry to add
  26503. */
  26504. Scene.prototype.addGeometry = function (newGeometry) {
  26505. this.geometries.push(newGeometry);
  26506. };
  26507. /**
  26508. * Adds the given action manager to this scene
  26509. * @param newActionManager The action manager to add
  26510. */
  26511. Scene.prototype.addActionManager = function (newActionManager) {
  26512. this.actionManagers.push(newActionManager);
  26513. };
  26514. /**
  26515. * Adds the given texture to this scene.
  26516. * @param newTexture The texture to add
  26517. */
  26518. Scene.prototype.addTexture = function (newTexture) {
  26519. this.textures.push(newTexture);
  26520. };
  26521. /**
  26522. * Switch active camera
  26523. * @param newCamera defines the new active camera
  26524. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26525. */
  26526. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26527. if (attachControl === void 0) { attachControl = true; }
  26528. var canvas = this._engine.getRenderingCanvas();
  26529. if (!canvas) {
  26530. return;
  26531. }
  26532. if (this.activeCamera) {
  26533. this.activeCamera.detachControl(canvas);
  26534. }
  26535. this.activeCamera = newCamera;
  26536. if (attachControl) {
  26537. newCamera.attachControl(canvas);
  26538. }
  26539. };
  26540. /**
  26541. * sets the active camera of the scene using its ID
  26542. * @param id defines the camera's ID
  26543. * @return the new active camera or null if none found.
  26544. */
  26545. Scene.prototype.setActiveCameraByID = function (id) {
  26546. var camera = this.getCameraByID(id);
  26547. if (camera) {
  26548. this.activeCamera = camera;
  26549. return camera;
  26550. }
  26551. return null;
  26552. };
  26553. /**
  26554. * sets the active camera of the scene using its name
  26555. * @param name defines the camera's name
  26556. * @returns the new active camera or null if none found.
  26557. */
  26558. Scene.prototype.setActiveCameraByName = function (name) {
  26559. var camera = this.getCameraByName(name);
  26560. if (camera) {
  26561. this.activeCamera = camera;
  26562. return camera;
  26563. }
  26564. return null;
  26565. };
  26566. /**
  26567. * get an animation group using its name
  26568. * @param name defines the material's name
  26569. * @return the animation group or null if none found.
  26570. */
  26571. Scene.prototype.getAnimationGroupByName = function (name) {
  26572. for (var index = 0; index < this.animationGroups.length; index++) {
  26573. if (this.animationGroups[index].name === name) {
  26574. return this.animationGroups[index];
  26575. }
  26576. }
  26577. return null;
  26578. };
  26579. /**
  26580. * get a material using its id
  26581. * @param id defines the material's ID
  26582. * @return the material or null if none found.
  26583. */
  26584. Scene.prototype.getMaterialByID = function (id) {
  26585. for (var index = 0; index < this.materials.length; index++) {
  26586. if (this.materials[index].id === id) {
  26587. return this.materials[index];
  26588. }
  26589. }
  26590. return null;
  26591. };
  26592. /**
  26593. * Gets a material using its name
  26594. * @param name defines the material's name
  26595. * @return the material or null if none found.
  26596. */
  26597. Scene.prototype.getMaterialByName = function (name) {
  26598. for (var index = 0; index < this.materials.length; index++) {
  26599. if (this.materials[index].name === name) {
  26600. return this.materials[index];
  26601. }
  26602. }
  26603. return null;
  26604. };
  26605. /**
  26606. * Gets a camera using its id
  26607. * @param id defines the id to look for
  26608. * @returns the camera or null if not found
  26609. */
  26610. Scene.prototype.getCameraByID = function (id) {
  26611. for (var index = 0; index < this.cameras.length; index++) {
  26612. if (this.cameras[index].id === id) {
  26613. return this.cameras[index];
  26614. }
  26615. }
  26616. return null;
  26617. };
  26618. /**
  26619. * Gets a camera using its unique id
  26620. * @param uniqueId defines the unique id to look for
  26621. * @returns the camera or null if not found
  26622. */
  26623. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26624. for (var index = 0; index < this.cameras.length; index++) {
  26625. if (this.cameras[index].uniqueId === uniqueId) {
  26626. return this.cameras[index];
  26627. }
  26628. }
  26629. return null;
  26630. };
  26631. /**
  26632. * Gets a camera using its name
  26633. * @param name defines the camera's name
  26634. * @return the camera or null if none found.
  26635. */
  26636. Scene.prototype.getCameraByName = function (name) {
  26637. for (var index = 0; index < this.cameras.length; index++) {
  26638. if (this.cameras[index].name === name) {
  26639. return this.cameras[index];
  26640. }
  26641. }
  26642. return null;
  26643. };
  26644. /**
  26645. * Gets a bone using its id
  26646. * @param id defines the bone's id
  26647. * @return the bone or null if not found
  26648. */
  26649. Scene.prototype.getBoneByID = function (id) {
  26650. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26651. var skeleton = this.skeletons[skeletonIndex];
  26652. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26653. if (skeleton.bones[boneIndex].id === id) {
  26654. return skeleton.bones[boneIndex];
  26655. }
  26656. }
  26657. }
  26658. return null;
  26659. };
  26660. /**
  26661. * Gets a bone using its id
  26662. * @param name defines the bone's name
  26663. * @return the bone or null if not found
  26664. */
  26665. Scene.prototype.getBoneByName = function (name) {
  26666. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26667. var skeleton = this.skeletons[skeletonIndex];
  26668. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26669. if (skeleton.bones[boneIndex].name === name) {
  26670. return skeleton.bones[boneIndex];
  26671. }
  26672. }
  26673. }
  26674. return null;
  26675. };
  26676. /**
  26677. * Gets a light node using its name
  26678. * @param name defines the the light's name
  26679. * @return the light or null if none found.
  26680. */
  26681. Scene.prototype.getLightByName = function (name) {
  26682. for (var index = 0; index < this.lights.length; index++) {
  26683. if (this.lights[index].name === name) {
  26684. return this.lights[index];
  26685. }
  26686. }
  26687. return null;
  26688. };
  26689. /**
  26690. * Gets a light node using its id
  26691. * @param id defines the light's id
  26692. * @return the light or null if none found.
  26693. */
  26694. Scene.prototype.getLightByID = function (id) {
  26695. for (var index = 0; index < this.lights.length; index++) {
  26696. if (this.lights[index].id === id) {
  26697. return this.lights[index];
  26698. }
  26699. }
  26700. return null;
  26701. };
  26702. /**
  26703. * Gets a light node using its scene-generated unique ID
  26704. * @param uniqueId defines the light's unique id
  26705. * @return the light or null if none found.
  26706. */
  26707. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26708. for (var index = 0; index < this.lights.length; index++) {
  26709. if (this.lights[index].uniqueId === uniqueId) {
  26710. return this.lights[index];
  26711. }
  26712. }
  26713. return null;
  26714. };
  26715. /**
  26716. * Gets a particle system by id
  26717. * @param id defines the particle system id
  26718. * @return the corresponding system or null if none found
  26719. */
  26720. Scene.prototype.getParticleSystemByID = function (id) {
  26721. for (var index = 0; index < this.particleSystems.length; index++) {
  26722. if (this.particleSystems[index].id === id) {
  26723. return this.particleSystems[index];
  26724. }
  26725. }
  26726. return null;
  26727. };
  26728. /**
  26729. * Gets a geometry using its ID
  26730. * @param id defines the geometry's id
  26731. * @return the geometry or null if none found.
  26732. */
  26733. Scene.prototype.getGeometryByID = function (id) {
  26734. for (var index = 0; index < this.geometries.length; index++) {
  26735. if (this.geometries[index].id === id) {
  26736. return this.geometries[index];
  26737. }
  26738. }
  26739. return null;
  26740. };
  26741. /**
  26742. * Add a new geometry to this scene
  26743. * @param geometry defines the geometry to be added to the scene.
  26744. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26745. * @return a boolean defining if the geometry was added or not
  26746. */
  26747. Scene.prototype.pushGeometry = function (geometry, force) {
  26748. if (!force && this.getGeometryByID(geometry.id)) {
  26749. return false;
  26750. }
  26751. this.geometries.push(geometry);
  26752. //notify the collision coordinator
  26753. if (this.collisionCoordinator) {
  26754. this.collisionCoordinator.onGeometryAdded(geometry);
  26755. }
  26756. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26757. return true;
  26758. };
  26759. /**
  26760. * Removes an existing geometry
  26761. * @param geometry defines the geometry to be removed from the scene
  26762. * @return a boolean defining if the geometry was removed or not
  26763. */
  26764. Scene.prototype.removeGeometry = function (geometry) {
  26765. var index = this.geometries.indexOf(geometry);
  26766. if (index > -1) {
  26767. this.geometries.splice(index, 1);
  26768. //notify the collision coordinator
  26769. if (this.collisionCoordinator) {
  26770. this.collisionCoordinator.onGeometryDeleted(geometry);
  26771. }
  26772. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26773. return true;
  26774. }
  26775. return false;
  26776. };
  26777. /**
  26778. * Gets the list of geometries attached to the scene
  26779. * @returns an array of Geometry
  26780. */
  26781. Scene.prototype.getGeometries = function () {
  26782. return this.geometries;
  26783. };
  26784. /**
  26785. * Gets the first added mesh found of a given ID
  26786. * @param id defines the id to search for
  26787. * @return the mesh found or null if not found at all
  26788. */
  26789. Scene.prototype.getMeshByID = function (id) {
  26790. for (var index = 0; index < this.meshes.length; index++) {
  26791. if (this.meshes[index].id === id) {
  26792. return this.meshes[index];
  26793. }
  26794. }
  26795. return null;
  26796. };
  26797. /**
  26798. * Gets a list of meshes using their id
  26799. * @param id defines the id to search for
  26800. * @returns a list of meshes
  26801. */
  26802. Scene.prototype.getMeshesByID = function (id) {
  26803. return this.meshes.filter(function (m) {
  26804. return m.id === id;
  26805. });
  26806. };
  26807. /**
  26808. * Gets the first added transform node found of a given ID
  26809. * @param id defines the id to search for
  26810. * @return the found transform node or null if not found at all.
  26811. */
  26812. Scene.prototype.getTransformNodeByID = function (id) {
  26813. for (var index = 0; index < this.transformNodes.length; index++) {
  26814. if (this.transformNodes[index].id === id) {
  26815. return this.transformNodes[index];
  26816. }
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * Gets a list of transform nodes using their id
  26822. * @param id defines the id to search for
  26823. * @returns a list of transform nodes
  26824. */
  26825. Scene.prototype.getTransformNodesByID = function (id) {
  26826. return this.transformNodes.filter(function (m) {
  26827. return m.id === id;
  26828. });
  26829. };
  26830. /**
  26831. * Gets a mesh with its auto-generated unique id
  26832. * @param uniqueId defines the unique id to search for
  26833. * @return the found mesh or null if not found at all.
  26834. */
  26835. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26836. for (var index = 0; index < this.meshes.length; index++) {
  26837. if (this.meshes[index].uniqueId === uniqueId) {
  26838. return this.meshes[index];
  26839. }
  26840. }
  26841. return null;
  26842. };
  26843. /**
  26844. * Gets a the last added mesh using a given id
  26845. * @param id defines the id to search for
  26846. * @return the found mesh or null if not found at all.
  26847. */
  26848. Scene.prototype.getLastMeshByID = function (id) {
  26849. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26850. if (this.meshes[index].id === id) {
  26851. return this.meshes[index];
  26852. }
  26853. }
  26854. return null;
  26855. };
  26856. /**
  26857. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26858. * @param id defines the id to search for
  26859. * @return the found node or null if not found at all
  26860. */
  26861. Scene.prototype.getLastEntryByID = function (id) {
  26862. var index;
  26863. for (index = this.meshes.length - 1; index >= 0; index--) {
  26864. if (this.meshes[index].id === id) {
  26865. return this.meshes[index];
  26866. }
  26867. }
  26868. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26869. if (this.transformNodes[index].id === id) {
  26870. return this.transformNodes[index];
  26871. }
  26872. }
  26873. for (index = this.cameras.length - 1; index >= 0; index--) {
  26874. if (this.cameras[index].id === id) {
  26875. return this.cameras[index];
  26876. }
  26877. }
  26878. for (index = this.lights.length - 1; index >= 0; index--) {
  26879. if (this.lights[index].id === id) {
  26880. return this.lights[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a node (Mesh, Camera, Light) using a given id
  26887. * @param id defines the id to search for
  26888. * @return the found node or null if not found at all
  26889. */
  26890. Scene.prototype.getNodeByID = function (id) {
  26891. var mesh = this.getMeshByID(id);
  26892. if (mesh) {
  26893. return mesh;
  26894. }
  26895. var light = this.getLightByID(id);
  26896. if (light) {
  26897. return light;
  26898. }
  26899. var camera = this.getCameraByID(id);
  26900. if (camera) {
  26901. return camera;
  26902. }
  26903. var bone = this.getBoneByID(id);
  26904. return bone;
  26905. };
  26906. /**
  26907. * Gets a node (Mesh, Camera, Light) using a given name
  26908. * @param name defines the name to search for
  26909. * @return the found node or null if not found at all.
  26910. */
  26911. Scene.prototype.getNodeByName = function (name) {
  26912. var mesh = this.getMeshByName(name);
  26913. if (mesh) {
  26914. return mesh;
  26915. }
  26916. var light = this.getLightByName(name);
  26917. if (light) {
  26918. return light;
  26919. }
  26920. var camera = this.getCameraByName(name);
  26921. if (camera) {
  26922. return camera;
  26923. }
  26924. var bone = this.getBoneByName(name);
  26925. return bone;
  26926. };
  26927. /**
  26928. * Gets a mesh using a given name
  26929. * @param name defines the name to search for
  26930. * @return the found mesh or null if not found at all.
  26931. */
  26932. Scene.prototype.getMeshByName = function (name) {
  26933. for (var index = 0; index < this.meshes.length; index++) {
  26934. if (this.meshes[index].name === name) {
  26935. return this.meshes[index];
  26936. }
  26937. }
  26938. return null;
  26939. };
  26940. /**
  26941. * Gets a transform node using a given name
  26942. * @param name defines the name to search for
  26943. * @return the found transform node or null if not found at all.
  26944. */
  26945. Scene.prototype.getTransformNodeByName = function (name) {
  26946. for (var index = 0; index < this.transformNodes.length; index++) {
  26947. if (this.transformNodes[index].name === name) {
  26948. return this.transformNodes[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a sound using a given name
  26955. * @param name defines the name to search for
  26956. * @return the found sound or null if not found at all.
  26957. */
  26958. Scene.prototype.getSoundByName = function (name) {
  26959. var index;
  26960. if (BABYLON.AudioEngine) {
  26961. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26962. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26963. return this.mainSoundTrack.soundCollection[index];
  26964. }
  26965. }
  26966. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26967. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26968. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26969. return this.soundTracks[sdIndex].soundCollection[index];
  26970. }
  26971. }
  26972. }
  26973. }
  26974. return null;
  26975. };
  26976. /**
  26977. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26978. * @param id defines the id to search for
  26979. * @return the found skeleton or null if not found at all.
  26980. */
  26981. Scene.prototype.getLastSkeletonByID = function (id) {
  26982. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26983. if (this.skeletons[index].id === id) {
  26984. return this.skeletons[index];
  26985. }
  26986. }
  26987. return null;
  26988. };
  26989. /**
  26990. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26991. * @param id defines the id to search for
  26992. * @return the found skeleton or null if not found at all.
  26993. */
  26994. Scene.prototype.getSkeletonById = function (id) {
  26995. for (var index = 0; index < this.skeletons.length; index++) {
  26996. if (this.skeletons[index].id === id) {
  26997. return this.skeletons[index];
  26998. }
  26999. }
  27000. return null;
  27001. };
  27002. /**
  27003. * Gets a skeleton using a given name
  27004. * @param name defines the name to search for
  27005. * @return the found skeleton or null if not found at all.
  27006. */
  27007. Scene.prototype.getSkeletonByName = function (name) {
  27008. for (var index = 0; index < this.skeletons.length; index++) {
  27009. if (this.skeletons[index].name === name) {
  27010. return this.skeletons[index];
  27011. }
  27012. }
  27013. return null;
  27014. };
  27015. /**
  27016. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27017. * @param id defines the id to search for
  27018. * @return the found morph target manager or null if not found at all.
  27019. */
  27020. Scene.prototype.getMorphTargetManagerById = function (id) {
  27021. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27022. if (this.morphTargetManagers[index].uniqueId === id) {
  27023. return this.morphTargetManagers[index];
  27024. }
  27025. }
  27026. return null;
  27027. };
  27028. /**
  27029. * Gets a boolean indicating if the given mesh is active
  27030. * @param mesh defines the mesh to look for
  27031. * @returns true if the mesh is in the active list
  27032. */
  27033. Scene.prototype.isActiveMesh = function (mesh) {
  27034. return (this._activeMeshes.indexOf(mesh) !== -1);
  27035. };
  27036. Object.defineProperty(Scene.prototype, "uid", {
  27037. /**
  27038. * Return a unique id as a string which can serve as an identifier for the scene
  27039. */
  27040. get: function () {
  27041. if (!this._uid) {
  27042. this._uid = BABYLON.Tools.RandomId();
  27043. }
  27044. return this._uid;
  27045. },
  27046. enumerable: true,
  27047. configurable: true
  27048. });
  27049. /**
  27050. * Add an externaly attached data from its key.
  27051. * This method call will fail and return false, if such key already exists.
  27052. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27053. * @param key the unique key that identifies the data
  27054. * @param data the data object to associate to the key for this Engine instance
  27055. * @return true if no such key were already present and the data was added successfully, false otherwise
  27056. */
  27057. Scene.prototype.addExternalData = function (key, data) {
  27058. if (!this._externalData) {
  27059. this._externalData = new BABYLON.StringDictionary();
  27060. }
  27061. return this._externalData.add(key, data);
  27062. };
  27063. /**
  27064. * Get an externaly attached data from its key
  27065. * @param key the unique key that identifies the data
  27066. * @return the associated data, if present (can be null), or undefined if not present
  27067. */
  27068. Scene.prototype.getExternalData = function (key) {
  27069. if (!this._externalData) {
  27070. return null;
  27071. }
  27072. return this._externalData.get(key);
  27073. };
  27074. /**
  27075. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27076. * @param key the unique key that identifies the data
  27077. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27078. * @return the associated data, can be null if the factory returned null.
  27079. */
  27080. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27081. if (!this._externalData) {
  27082. this._externalData = new BABYLON.StringDictionary();
  27083. }
  27084. return this._externalData.getOrAddWithFactory(key, factory);
  27085. };
  27086. /**
  27087. * Remove an externaly attached data from the Engine instance
  27088. * @param key the unique key that identifies the data
  27089. * @return true if the data was successfully removed, false if it doesn't exist
  27090. */
  27091. Scene.prototype.removeExternalData = function (key) {
  27092. return this._externalData.remove(key);
  27093. };
  27094. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27095. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27096. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27097. var step = _a[_i];
  27098. step.action(mesh, subMesh);
  27099. }
  27100. var material = subMesh.getMaterial();
  27101. if (material !== null && material !== undefined) {
  27102. // Render targets
  27103. if (material.getRenderTargetTextures !== undefined) {
  27104. if (this._processedMaterials.indexOf(material) === -1) {
  27105. this._processedMaterials.push(material);
  27106. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27107. }
  27108. }
  27109. // Dispatch
  27110. this._activeIndices.addCount(subMesh.indexCount, false);
  27111. this._renderingManager.dispatch(subMesh, mesh, material);
  27112. }
  27113. }
  27114. };
  27115. /**
  27116. * Clear the processed materials smart array preventing retention point in material dispose.
  27117. */
  27118. Scene.prototype.freeProcessedMaterials = function () {
  27119. this._processedMaterials.dispose();
  27120. };
  27121. /**
  27122. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27123. */
  27124. Scene.prototype.freeActiveMeshes = function () {
  27125. this._activeMeshes.dispose();
  27126. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27127. this.activeCamera._activeMeshes.dispose();
  27128. }
  27129. if (this.activeCameras) {
  27130. for (var i = 0; i < this.activeCameras.length; i++) {
  27131. var activeCamera = this.activeCameras[i];
  27132. if (activeCamera && activeCamera._activeMeshes) {
  27133. activeCamera._activeMeshes.dispose();
  27134. }
  27135. }
  27136. }
  27137. };
  27138. /**
  27139. * Clear the info related to rendering groups preventing retention points during dispose.
  27140. */
  27141. Scene.prototype.freeRenderingGroups = function () {
  27142. if (this._renderingManager) {
  27143. this._renderingManager.freeRenderingGroups();
  27144. }
  27145. if (this.textures) {
  27146. for (var i = 0; i < this.textures.length; i++) {
  27147. var texture = this.textures[i];
  27148. if (texture && texture.renderList) {
  27149. texture.freeRenderingGroups();
  27150. }
  27151. }
  27152. }
  27153. };
  27154. /** @hidden */
  27155. Scene.prototype._isInIntermediateRendering = function () {
  27156. return this._intermediateRendering;
  27157. };
  27158. /**
  27159. * Defines the current active mesh candidate provider
  27160. * @param provider defines the provider to use
  27161. */
  27162. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27163. this._activeMeshCandidateProvider = provider;
  27164. };
  27165. /**
  27166. * Gets the current active mesh candidate provider
  27167. * @returns the current active mesh candidate provider
  27168. */
  27169. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27170. return this._activeMeshCandidateProvider;
  27171. };
  27172. /**
  27173. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27174. * @returns the current scene
  27175. */
  27176. Scene.prototype.freezeActiveMeshes = function () {
  27177. if (!this.activeCamera) {
  27178. return this;
  27179. }
  27180. if (!this._frustumPlanes) {
  27181. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27182. }
  27183. this._evaluateActiveMeshes();
  27184. this._activeMeshesFrozen = true;
  27185. return this;
  27186. };
  27187. /**
  27188. * Use this function to restart evaluating active meshes on every frame
  27189. * @returns the current scene
  27190. */
  27191. Scene.prototype.unfreezeActiveMeshes = function () {
  27192. this._activeMeshesFrozen = false;
  27193. return this;
  27194. };
  27195. Scene.prototype._evaluateActiveMeshes = function () {
  27196. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27197. return;
  27198. }
  27199. if (!this.activeCamera) {
  27200. return;
  27201. }
  27202. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27203. this.activeCamera._activeMeshes.reset();
  27204. this._activeMeshes.reset();
  27205. this._renderingManager.reset();
  27206. this._processedMaterials.reset();
  27207. this._activeParticleSystems.reset();
  27208. this._activeSkeletons.reset();
  27209. this._softwareSkinnedMeshes.reset();
  27210. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27211. var step = _a[_i];
  27212. step.action();
  27213. }
  27214. // Meshes
  27215. var meshes;
  27216. var len;
  27217. var checkIsEnabled = true;
  27218. // Determine mesh candidates
  27219. if (this._activeMeshCandidateProvider !== undefined) {
  27220. // Use _activeMeshCandidateProvider
  27221. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27222. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27223. if (meshes !== undefined) {
  27224. len = meshes.length;
  27225. }
  27226. else {
  27227. len = 0;
  27228. }
  27229. }
  27230. else if (this._selectionOctree !== undefined) {
  27231. // Octree
  27232. var selection = this._selectionOctree.select(this._frustumPlanes);
  27233. meshes = selection.data;
  27234. len = selection.length;
  27235. }
  27236. else {
  27237. // Full scene traversal
  27238. len = this.meshes.length;
  27239. meshes = this.meshes;
  27240. }
  27241. // Check each mesh
  27242. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27243. mesh = meshes[meshIndex];
  27244. if (mesh.isBlocked) {
  27245. continue;
  27246. }
  27247. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27248. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27249. continue;
  27250. }
  27251. mesh.computeWorldMatrix();
  27252. // Intersections
  27253. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27254. this._meshesForIntersections.pushNoDuplicate(mesh);
  27255. }
  27256. // Switch to current LOD
  27257. meshLOD = mesh.getLOD(this.activeCamera);
  27258. if (meshLOD === undefined || meshLOD === null) {
  27259. continue;
  27260. }
  27261. mesh._preActivate();
  27262. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27263. this._activeMeshes.push(mesh);
  27264. this.activeCamera._activeMeshes.push(mesh);
  27265. mesh._activate(this._renderId);
  27266. if (meshLOD !== mesh) {
  27267. meshLOD._activate(this._renderId);
  27268. }
  27269. this._activeMesh(mesh, meshLOD);
  27270. }
  27271. }
  27272. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27273. // Particle systems
  27274. if (this.particlesEnabled) {
  27275. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27276. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27277. var particleSystem = this.particleSystems[particleIndex];
  27278. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27279. continue;
  27280. }
  27281. var emitter = particleSystem.emitter;
  27282. if (!emitter.position || emitter.isEnabled()) {
  27283. this._activeParticleSystems.push(particleSystem);
  27284. particleSystem.animate();
  27285. this._renderingManager.dispatchParticles(particleSystem);
  27286. }
  27287. }
  27288. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27289. }
  27290. };
  27291. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27292. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27293. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27294. mesh.skeleton.prepare();
  27295. }
  27296. if (!mesh.computeBonesUsingShaders) {
  27297. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27298. }
  27299. }
  27300. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27301. var step = _a[_i];
  27302. step.action(sourceMesh, mesh);
  27303. }
  27304. if (mesh !== undefined && mesh !== null
  27305. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27306. // Submeshes Octrees
  27307. var len;
  27308. var subMeshes;
  27309. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27310. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27311. len = intersections.length;
  27312. subMeshes = intersections.data;
  27313. }
  27314. else {
  27315. subMeshes = mesh.subMeshes;
  27316. len = subMeshes.length;
  27317. }
  27318. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27319. subMesh = subMeshes[subIndex];
  27320. this._evaluateSubMesh(subMesh, mesh);
  27321. }
  27322. }
  27323. };
  27324. /**
  27325. * Update the transform matrix to update from the current active camera
  27326. * @param force defines a boolean used to force the update even if cache is up to date
  27327. */
  27328. Scene.prototype.updateTransformMatrix = function (force) {
  27329. if (!this.activeCamera) {
  27330. return;
  27331. }
  27332. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27333. };
  27334. /**
  27335. * 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)
  27336. * @param alternateCamera defines the camera to use
  27337. */
  27338. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27339. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27340. };
  27341. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27342. if (camera && camera._skipRendering) {
  27343. return;
  27344. }
  27345. var engine = this._engine;
  27346. this.activeCamera = camera;
  27347. if (!this.activeCamera)
  27348. throw new Error("Active camera not set");
  27349. // Viewport
  27350. engine.setViewport(this.activeCamera.viewport);
  27351. // Camera
  27352. this.resetCachedMaterial();
  27353. this._renderId++;
  27354. this.updateTransformMatrix();
  27355. if (camera._alternateCamera) {
  27356. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27357. this._alternateRendering = true;
  27358. }
  27359. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27360. // Meshes
  27361. this._evaluateActiveMeshes();
  27362. // Software skinning
  27363. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27364. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27365. mesh.applySkeleton(mesh.skeleton);
  27366. }
  27367. // Render targets
  27368. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27369. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27370. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27371. }
  27372. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27373. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27374. }
  27375. if (this.renderTargetsEnabled) {
  27376. this._intermediateRendering = true;
  27377. if (this._renderTargets.length > 0) {
  27378. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27379. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27380. var renderTarget = this._renderTargets.data[renderIndex];
  27381. if (renderTarget._shouldRender()) {
  27382. this._renderId++;
  27383. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27384. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27385. }
  27386. }
  27387. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27388. this._renderId++;
  27389. }
  27390. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27391. var step = _a[_i];
  27392. step.action(this.activeCamera);
  27393. }
  27394. this._intermediateRendering = false;
  27395. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27396. }
  27397. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27398. // Prepare Frame
  27399. if (this.postProcessManager) {
  27400. this.postProcessManager._prepareFrame();
  27401. }
  27402. // Before Camera Draw
  27403. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27404. var step = _c[_b];
  27405. step.action(this.activeCamera);
  27406. }
  27407. // Render
  27408. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27409. this._renderingManager.render(null, null, true, true);
  27410. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27411. // After Camera Draw
  27412. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27413. var step = _e[_d];
  27414. step.action(this.activeCamera);
  27415. }
  27416. // Finalize frame
  27417. if (this.postProcessManager) {
  27418. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27419. }
  27420. // Reset some special arrays
  27421. this._renderTargets.reset();
  27422. this._alternateRendering = false;
  27423. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27424. };
  27425. Scene.prototype._processSubCameras = function (camera) {
  27426. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27427. this._renderForCamera(camera);
  27428. return;
  27429. }
  27430. // rig cameras
  27431. for (var index = 0; index < camera._rigCameras.length; index++) {
  27432. this._renderForCamera(camera._rigCameras[index], camera);
  27433. }
  27434. this.activeCamera = camera;
  27435. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27436. };
  27437. Scene.prototype._checkIntersections = function () {
  27438. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27439. var sourceMesh = this._meshesForIntersections.data[index];
  27440. if (!sourceMesh.actionManager) {
  27441. continue;
  27442. }
  27443. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27444. var action = sourceMesh.actionManager.actions[actionIndex];
  27445. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27446. var parameters = action.getTriggerParameter();
  27447. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27448. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27449. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27450. if (areIntersecting && currentIntersectionInProgress === -1) {
  27451. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27452. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27453. sourceMesh._intersectionsInProgress.push(otherMesh);
  27454. }
  27455. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27456. sourceMesh._intersectionsInProgress.push(otherMesh);
  27457. }
  27458. }
  27459. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27460. //They intersected, and now they don't.
  27461. //is this trigger an exit trigger? execute an event.
  27462. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27463. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27464. }
  27465. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27466. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27467. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27468. return otherMesh === parameterMesh;
  27469. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27470. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27471. }
  27472. }
  27473. }
  27474. }
  27475. }
  27476. };
  27477. /**
  27478. * Render the scene
  27479. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27480. */
  27481. Scene.prototype.render = function (updateCameras) {
  27482. if (updateCameras === void 0) { updateCameras = true; }
  27483. if (this.isDisposed) {
  27484. return;
  27485. }
  27486. // Register components that have been associated lately to the scene.
  27487. this._registerTransientComponents();
  27488. this._activeParticles.fetchNewFrame();
  27489. this._totalVertices.fetchNewFrame();
  27490. this._activeIndices.fetchNewFrame();
  27491. this._activeBones.fetchNewFrame();
  27492. this._meshesForIntersections.reset();
  27493. this.resetCachedMaterial();
  27494. this.onBeforeAnimationsObservable.notifyObservers(this);
  27495. // Actions
  27496. if (this.actionManager) {
  27497. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27498. }
  27499. //Simplification Queue
  27500. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27501. this.simplificationQueue.executeNext();
  27502. }
  27503. if (this._engine.isDeterministicLockStep()) {
  27504. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27505. var defaultFPS = (60.0 / 1000.0);
  27506. var defaultFrameTime = 1000 / 60; // frame time in MS
  27507. if (this._physicsEngine) {
  27508. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27509. }
  27510. var stepsTaken = 0;
  27511. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27512. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27513. internalSteps = Math.min(internalSteps, maxSubSteps);
  27514. do {
  27515. this.onBeforeStepObservable.notifyObservers(this);
  27516. // Animations
  27517. this._animationRatio = defaultFrameTime * defaultFPS;
  27518. this._animate();
  27519. this.onAfterAnimationsObservable.notifyObservers(this);
  27520. // Physics
  27521. if (this._physicsEngine) {
  27522. this.onBeforePhysicsObservable.notifyObservers(this);
  27523. this._physicsEngine._step(defaultFrameTime / 1000);
  27524. this.onAfterPhysicsObservable.notifyObservers(this);
  27525. }
  27526. this.onAfterStepObservable.notifyObservers(this);
  27527. this._currentStepId++;
  27528. stepsTaken++;
  27529. deltaTime -= defaultFrameTime;
  27530. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27531. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27532. }
  27533. else {
  27534. // Animations
  27535. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27536. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27537. this._animate();
  27538. this.onAfterAnimationsObservable.notifyObservers(this);
  27539. // Physics
  27540. if (this._physicsEngine) {
  27541. this.onBeforePhysicsObservable.notifyObservers(this);
  27542. this._physicsEngine._step(deltaTime / 1000.0);
  27543. this.onAfterPhysicsObservable.notifyObservers(this);
  27544. }
  27545. }
  27546. // Before camera update steps
  27547. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27548. var step = _a[_i];
  27549. step.action();
  27550. }
  27551. // Update Cameras
  27552. if (updateCameras) {
  27553. if (this.activeCameras.length > 0) {
  27554. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27555. var camera = this.activeCameras[cameraIndex];
  27556. camera.update();
  27557. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27558. // rig cameras
  27559. for (var index = 0; index < camera._rigCameras.length; index++) {
  27560. camera._rigCameras[index].update();
  27561. }
  27562. }
  27563. }
  27564. }
  27565. else if (this.activeCamera) {
  27566. this.activeCamera.update();
  27567. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27568. // rig cameras
  27569. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27570. this.activeCamera._rigCameras[index].update();
  27571. }
  27572. }
  27573. }
  27574. }
  27575. // Before render
  27576. this.onBeforeRenderObservable.notifyObservers(this);
  27577. // Customs render targets
  27578. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27579. var engine = this.getEngine();
  27580. var currentActiveCamera = this.activeCamera;
  27581. if (this.renderTargetsEnabled) {
  27582. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27583. this._intermediateRendering = true;
  27584. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27585. var renderTarget = this.customRenderTargets[customIndex];
  27586. if (renderTarget._shouldRender()) {
  27587. this._renderId++;
  27588. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27589. if (!this.activeCamera)
  27590. throw new Error("Active camera not set");
  27591. // Viewport
  27592. engine.setViewport(this.activeCamera.viewport);
  27593. // Camera
  27594. this.updateTransformMatrix();
  27595. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27596. }
  27597. }
  27598. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27599. this._intermediateRendering = false;
  27600. this._renderId++;
  27601. }
  27602. // Restore back buffer
  27603. if (this.customRenderTargets.length > 0) {
  27604. engine.restoreDefaultFramebuffer();
  27605. }
  27606. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27607. this.activeCamera = currentActiveCamera;
  27608. // Procedural textures
  27609. if (this.proceduralTexturesEnabled) {
  27610. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27611. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27612. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27613. if (proceduralTexture._shouldRender()) {
  27614. proceduralTexture.render();
  27615. }
  27616. }
  27617. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27618. }
  27619. // Clear
  27620. if (this.autoClearDepthAndStencil || this.autoClear) {
  27621. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27622. }
  27623. // Shadows
  27624. if (this.shadowsEnabled) {
  27625. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27626. var light = this.lights[lightIndex];
  27627. var shadowGenerator = light.getShadowGenerator();
  27628. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27629. var shadowMap = (shadowGenerator.getShadowMap());
  27630. if (this.textures.indexOf(shadowMap) !== -1) {
  27631. this._renderTargets.push(shadowMap);
  27632. }
  27633. }
  27634. }
  27635. }
  27636. // Depth renderer
  27637. for (var key in this._depthRenderer) {
  27638. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27639. }
  27640. // Geometry renderer
  27641. if (this._geometryBufferRenderer) {
  27642. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27643. }
  27644. // RenderPipeline
  27645. if (this._postProcessRenderPipelineManager) {
  27646. this._postProcessRenderPipelineManager.update();
  27647. }
  27648. // Multi-cameras?
  27649. if (this.activeCameras.length > 0) {
  27650. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27651. if (cameraIndex > 0) {
  27652. this._engine.clear(null, false, true, true);
  27653. }
  27654. this._processSubCameras(this.activeCameras[cameraIndex]);
  27655. }
  27656. }
  27657. else {
  27658. if (!this.activeCamera) {
  27659. throw new Error("No camera defined");
  27660. }
  27661. this._processSubCameras(this.activeCamera);
  27662. }
  27663. // Intersection checks
  27664. this._checkIntersections();
  27665. // Update the audio listener attached to the camera
  27666. if (BABYLON.AudioEngine) {
  27667. this._updateAudioParameters();
  27668. }
  27669. // After render
  27670. if (this.afterRender) {
  27671. this.afterRender();
  27672. }
  27673. this.onAfterRenderObservable.notifyObservers(this);
  27674. // Cleaning
  27675. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27676. var data = this._toBeDisposed.data[index];
  27677. if (data) {
  27678. data.dispose();
  27679. }
  27680. this._toBeDisposed[index] = null;
  27681. }
  27682. this._toBeDisposed.reset();
  27683. if (this.dumpNextRenderTargets) {
  27684. this.dumpNextRenderTargets = false;
  27685. }
  27686. this._activeBones.addCount(0, true);
  27687. this._activeIndices.addCount(0, true);
  27688. this._activeParticles.addCount(0, true);
  27689. };
  27690. Scene.prototype._updateAudioParameters = function () {
  27691. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27692. return;
  27693. }
  27694. var listeningCamera;
  27695. var audioEngine = BABYLON.Engine.audioEngine;
  27696. if (this.activeCameras.length > 0) {
  27697. listeningCamera = this.activeCameras[0];
  27698. }
  27699. else {
  27700. listeningCamera = this.activeCamera;
  27701. }
  27702. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27703. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27704. // for VR cameras
  27705. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27706. listeningCamera = listeningCamera.rigCameras[0];
  27707. }
  27708. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27709. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27710. cameraDirection.normalize();
  27711. // To avoid some errors on GearVR
  27712. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27713. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27714. }
  27715. var i;
  27716. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27717. var sound = this.mainSoundTrack.soundCollection[i];
  27718. if (sound.useCustomAttenuation) {
  27719. sound.updateDistanceFromListener();
  27720. }
  27721. }
  27722. for (i = 0; i < this.soundTracks.length; i++) {
  27723. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27724. sound = this.soundTracks[i].soundCollection[j];
  27725. if (sound.useCustomAttenuation) {
  27726. sound.updateDistanceFromListener();
  27727. }
  27728. }
  27729. }
  27730. }
  27731. };
  27732. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27733. // Audio
  27734. /**
  27735. * Gets or sets if audio support is enabled
  27736. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27737. */
  27738. get: function () {
  27739. return this._audioEnabled;
  27740. },
  27741. set: function (value) {
  27742. this._audioEnabled = value;
  27743. if (BABYLON.AudioEngine) {
  27744. if (this._audioEnabled) {
  27745. this._enableAudio();
  27746. }
  27747. else {
  27748. this._disableAudio();
  27749. }
  27750. }
  27751. },
  27752. enumerable: true,
  27753. configurable: true
  27754. });
  27755. Scene.prototype._disableAudio = function () {
  27756. var i;
  27757. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27758. this.mainSoundTrack.soundCollection[i].pause();
  27759. }
  27760. for (i = 0; i < this.soundTracks.length; i++) {
  27761. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27762. this.soundTracks[i].soundCollection[j].pause();
  27763. }
  27764. }
  27765. };
  27766. Scene.prototype._enableAudio = function () {
  27767. var i;
  27768. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27769. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27770. this.mainSoundTrack.soundCollection[i].play();
  27771. }
  27772. }
  27773. for (i = 0; i < this.soundTracks.length; i++) {
  27774. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27775. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27776. this.soundTracks[i].soundCollection[j].play();
  27777. }
  27778. }
  27779. }
  27780. };
  27781. Object.defineProperty(Scene.prototype, "headphone", {
  27782. /**
  27783. * Gets or sets if audio will be output to headphones
  27784. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27785. */
  27786. get: function () {
  27787. return this._headphone;
  27788. },
  27789. set: function (value) {
  27790. this._headphone = value;
  27791. if (BABYLON.AudioEngine) {
  27792. if (this._headphone) {
  27793. this._switchAudioModeForHeadphones();
  27794. }
  27795. else {
  27796. this._switchAudioModeForNormalSpeakers();
  27797. }
  27798. }
  27799. },
  27800. enumerable: true,
  27801. configurable: true
  27802. });
  27803. Scene.prototype._switchAudioModeForHeadphones = function () {
  27804. this.mainSoundTrack.switchPanningModelToHRTF();
  27805. for (var i = 0; i < this.soundTracks.length; i++) {
  27806. this.soundTracks[i].switchPanningModelToHRTF();
  27807. }
  27808. };
  27809. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27810. this.mainSoundTrack.switchPanningModelToEqualPower();
  27811. for (var i = 0; i < this.soundTracks.length; i++) {
  27812. this.soundTracks[i].switchPanningModelToEqualPower();
  27813. }
  27814. };
  27815. /**
  27816. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27817. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27818. * @returns the created depth renderer
  27819. */
  27820. Scene.prototype.enableDepthRenderer = function (camera) {
  27821. camera = camera || this.activeCamera;
  27822. if (!camera) {
  27823. throw "No camera available to enable depth renderer";
  27824. }
  27825. if (!this._depthRenderer[camera.id]) {
  27826. var textureType = 0;
  27827. if (this._engine.getCaps().textureHalfFloatRender) {
  27828. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27829. }
  27830. else if (this._engine.getCaps().textureFloatRender) {
  27831. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27832. }
  27833. else {
  27834. throw "Depth renderer does not support int texture type";
  27835. }
  27836. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27837. }
  27838. return this._depthRenderer[camera.id];
  27839. };
  27840. /**
  27841. * Disables a depth renderer for a given camera
  27842. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27843. */
  27844. Scene.prototype.disableDepthRenderer = function (camera) {
  27845. camera = camera || this.activeCamera;
  27846. if (!camera || !this._depthRenderer[camera.id]) {
  27847. return;
  27848. }
  27849. this._depthRenderer[camera.id].dispose();
  27850. delete this._depthRenderer[camera.id];
  27851. };
  27852. /**
  27853. * Enables a GeometryBufferRender and associates it with the scene
  27854. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27855. * @returns the GeometryBufferRenderer
  27856. */
  27857. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27858. if (ratio === void 0) { ratio = 1; }
  27859. if (this._geometryBufferRenderer) {
  27860. return this._geometryBufferRenderer;
  27861. }
  27862. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27863. if (!this._geometryBufferRenderer.isSupported) {
  27864. this._geometryBufferRenderer = null;
  27865. }
  27866. return this._geometryBufferRenderer;
  27867. };
  27868. /**
  27869. * Disables the GeometryBufferRender associated with the scene
  27870. */
  27871. Scene.prototype.disableGeometryBufferRenderer = function () {
  27872. if (!this._geometryBufferRenderer) {
  27873. return;
  27874. }
  27875. this._geometryBufferRenderer.dispose();
  27876. this._geometryBufferRenderer = null;
  27877. };
  27878. /**
  27879. * Freeze all materials
  27880. * A frozen material will not be updatable but should be faster to render
  27881. */
  27882. Scene.prototype.freezeMaterials = function () {
  27883. for (var i = 0; i < this.materials.length; i++) {
  27884. this.materials[i].freeze();
  27885. }
  27886. };
  27887. /**
  27888. * Unfreeze all materials
  27889. * A frozen material will not be updatable but should be faster to render
  27890. */
  27891. Scene.prototype.unfreezeMaterials = function () {
  27892. for (var i = 0; i < this.materials.length; i++) {
  27893. this.materials[i].unfreeze();
  27894. }
  27895. };
  27896. /**
  27897. * Releases all held ressources
  27898. */
  27899. Scene.prototype.dispose = function () {
  27900. this.beforeRender = null;
  27901. this.afterRender = null;
  27902. this.skeletons = [];
  27903. this.morphTargetManagers = [];
  27904. this._transientComponents = [];
  27905. this._isReadyForMeshStage.clear();
  27906. this._beforeEvaluateActiveMeshStage.clear();
  27907. this._evaluateSubMeshStage.clear();
  27908. this._activeMeshStage.clear();
  27909. this._cameraDrawRenderTargetStage.clear();
  27910. this._beforeCameraDrawStage.clear();
  27911. this._beforeRenderingGroupDrawStage.clear();
  27912. this._afterRenderingGroupDrawStage.clear();
  27913. this._afterCameraDrawStage.clear();
  27914. this._beforeCameraUpdateStage.clear();
  27915. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27916. var component = _a[_i];
  27917. component.dispose();
  27918. }
  27919. this.importedMeshesFiles = new Array();
  27920. this.stopAllAnimations();
  27921. this.resetCachedMaterial();
  27922. for (var key in this._depthRenderer) {
  27923. this._depthRenderer[key].dispose();
  27924. }
  27925. // Smart arrays
  27926. if (this.activeCamera) {
  27927. this.activeCamera._activeMeshes.dispose();
  27928. this.activeCamera = null;
  27929. }
  27930. this._activeMeshes.dispose();
  27931. this._renderingManager.dispose();
  27932. this._processedMaterials.dispose();
  27933. this._activeParticleSystems.dispose();
  27934. this._activeSkeletons.dispose();
  27935. this._softwareSkinnedMeshes.dispose();
  27936. this._renderTargets.dispose();
  27937. this._registeredForLateAnimationBindings.dispose();
  27938. this._meshesForIntersections.dispose();
  27939. this._toBeDisposed.dispose();
  27940. // Abort active requests
  27941. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27942. var request = _c[_b];
  27943. request.abort();
  27944. }
  27945. // Debug layer
  27946. if (this._debugLayer) {
  27947. this._debugLayer.hide();
  27948. }
  27949. // Events
  27950. this.onDisposeObservable.notifyObservers(this);
  27951. this.onDisposeObservable.clear();
  27952. this.onBeforeRenderObservable.clear();
  27953. this.onAfterRenderObservable.clear();
  27954. this.onBeforeRenderTargetsRenderObservable.clear();
  27955. this.onAfterRenderTargetsRenderObservable.clear();
  27956. this.onAfterStepObservable.clear();
  27957. this.onBeforeStepObservable.clear();
  27958. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27959. this.onAfterActiveMeshesEvaluationObservable.clear();
  27960. this.onBeforeParticlesRenderingObservable.clear();
  27961. this.onAfterParticlesRenderingObservable.clear();
  27962. this.onBeforeSpritesRenderingObservable.clear();
  27963. this.onAfterSpritesRenderingObservable.clear();
  27964. this.onBeforeDrawPhaseObservable.clear();
  27965. this.onAfterDrawPhaseObservable.clear();
  27966. this.onBeforePhysicsObservable.clear();
  27967. this.onAfterPhysicsObservable.clear();
  27968. this.onBeforeAnimationsObservable.clear();
  27969. this.onAfterAnimationsObservable.clear();
  27970. this.onDataLoadedObservable.clear();
  27971. this.detachControl();
  27972. // Release sounds & sounds tracks
  27973. if (BABYLON.AudioEngine) {
  27974. this.disposeSounds();
  27975. }
  27976. // VR Helper
  27977. if (this.VRHelper) {
  27978. this.VRHelper.dispose();
  27979. }
  27980. // Detach cameras
  27981. var canvas = this._engine.getRenderingCanvas();
  27982. if (canvas) {
  27983. var index;
  27984. for (index = 0; index < this.cameras.length; index++) {
  27985. this.cameras[index].detachControl(canvas);
  27986. }
  27987. }
  27988. // Release animation groups
  27989. while (this.animationGroups.length) {
  27990. this.animationGroups[0].dispose();
  27991. }
  27992. // Release lights
  27993. while (this.lights.length) {
  27994. this.lights[0].dispose();
  27995. }
  27996. // Release meshes
  27997. while (this.meshes.length) {
  27998. this.meshes[0].dispose(true);
  27999. }
  28000. while (this.transformNodes.length) {
  28001. this.removeTransformNode(this.transformNodes[0]);
  28002. }
  28003. // Release cameras
  28004. while (this.cameras.length) {
  28005. this.cameras[0].dispose();
  28006. }
  28007. // Release materials
  28008. if (this.defaultMaterial) {
  28009. this.defaultMaterial.dispose();
  28010. }
  28011. while (this.multiMaterials.length) {
  28012. this.multiMaterials[0].dispose();
  28013. }
  28014. while (this.materials.length) {
  28015. this.materials[0].dispose();
  28016. }
  28017. // Release particles
  28018. while (this.particleSystems.length) {
  28019. this.particleSystems[0].dispose();
  28020. }
  28021. // Release sprites
  28022. while (this.spriteManagers.length) {
  28023. this.spriteManagers[0].dispose();
  28024. }
  28025. // Release postProcesses
  28026. while (this.postProcesses.length) {
  28027. this.postProcesses[0].dispose();
  28028. }
  28029. // Release textures
  28030. while (this.textures.length) {
  28031. this.textures[0].dispose();
  28032. }
  28033. // Release UBO
  28034. this._sceneUbo.dispose();
  28035. if (this._alternateSceneUbo) {
  28036. this._alternateSceneUbo.dispose();
  28037. }
  28038. // Post-processes
  28039. this.postProcessManager.dispose();
  28040. if (this._postProcessRenderPipelineManager) {
  28041. this._postProcessRenderPipelineManager.dispose();
  28042. }
  28043. // Physics
  28044. if (this._physicsEngine) {
  28045. this.disablePhysicsEngine();
  28046. }
  28047. // Remove from engine
  28048. index = this._engine.scenes.indexOf(this);
  28049. if (index > -1) {
  28050. this._engine.scenes.splice(index, 1);
  28051. }
  28052. this._engine.wipeCaches(true);
  28053. this._isDisposed = true;
  28054. };
  28055. Object.defineProperty(Scene.prototype, "isDisposed", {
  28056. /**
  28057. * Gets if the scene is already disposed
  28058. */
  28059. get: function () {
  28060. return this._isDisposed;
  28061. },
  28062. enumerable: true,
  28063. configurable: true
  28064. });
  28065. /**
  28066. * Releases sounds & soundtracks
  28067. */
  28068. Scene.prototype.disposeSounds = function () {
  28069. if (!this._mainSoundTrack) {
  28070. return;
  28071. }
  28072. this.mainSoundTrack.dispose();
  28073. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28074. this.soundTracks[scIndex].dispose();
  28075. }
  28076. };
  28077. /**
  28078. * Call this function to reduce memory footprint of the scene.
  28079. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28080. */
  28081. Scene.prototype.clearCachedVertexData = function () {
  28082. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28083. var mesh = this.meshes[meshIndex];
  28084. var geometry = mesh.geometry;
  28085. if (geometry) {
  28086. geometry._indices = [];
  28087. for (var vbName in geometry._vertexBuffers) {
  28088. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28089. continue;
  28090. }
  28091. geometry._vertexBuffers[vbName]._buffer._data = null;
  28092. }
  28093. }
  28094. }
  28095. };
  28096. /**
  28097. * This function will remove the local cached buffer data from texture.
  28098. * It will save memory but will prevent the texture from being rebuilt
  28099. */
  28100. Scene.prototype.cleanCachedTextureBuffer = function () {
  28101. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28102. var baseTexture = _a[_i];
  28103. var buffer = baseTexture._buffer;
  28104. if (buffer) {
  28105. baseTexture._buffer = null;
  28106. }
  28107. }
  28108. };
  28109. // Octrees
  28110. /**
  28111. * Get the world extend vectors with an optional filter
  28112. *
  28113. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28114. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28115. */
  28116. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28117. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28118. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28119. filterPredicate = filterPredicate || (function () { return true; });
  28120. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28121. mesh.computeWorldMatrix(true);
  28122. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28123. return;
  28124. }
  28125. var boundingInfo = mesh.getBoundingInfo();
  28126. var minBox = boundingInfo.boundingBox.minimumWorld;
  28127. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28128. BABYLON.Tools.CheckExtends(minBox, min, max);
  28129. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28130. });
  28131. return {
  28132. min: min,
  28133. max: max
  28134. };
  28135. };
  28136. /**
  28137. * Creates or updates the octree used to boost selection (picking)
  28138. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28139. * @param maxCapacity defines the maximum capacity per leaf
  28140. * @param maxDepth defines the maximum depth of the octree
  28141. * @returns an octree of AbstractMesh
  28142. */
  28143. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28144. if (maxCapacity === void 0) { maxCapacity = 64; }
  28145. if (maxDepth === void 0) { maxDepth = 2; }
  28146. if (!this._selectionOctree) {
  28147. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28148. }
  28149. var worldExtends = this.getWorldExtends();
  28150. // Update octree
  28151. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28152. return this._selectionOctree;
  28153. };
  28154. // Picking
  28155. /**
  28156. * Creates a ray that can be used to pick in the scene
  28157. * @param x defines the x coordinate of the origin (on-screen)
  28158. * @param y defines the y coordinate of the origin (on-screen)
  28159. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28160. * @param camera defines the camera to use for the picking
  28161. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28162. * @returns a Ray
  28163. */
  28164. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28165. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28166. var result = BABYLON.Ray.Zero();
  28167. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28168. return result;
  28169. };
  28170. /**
  28171. * Creates a ray that can be used to pick in the scene
  28172. * @param x defines the x coordinate of the origin (on-screen)
  28173. * @param y defines the y coordinate of the origin (on-screen)
  28174. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28175. * @param result defines the ray where to store the picking ray
  28176. * @param camera defines the camera to use for the picking
  28177. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28178. * @returns the current scene
  28179. */
  28180. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28181. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28182. var engine = this._engine;
  28183. if (!camera) {
  28184. if (!this.activeCamera)
  28185. throw new Error("Active camera not set");
  28186. camera = this.activeCamera;
  28187. }
  28188. var cameraViewport = camera.viewport;
  28189. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28190. // Moving coordinates to local viewport world
  28191. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28192. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28193. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28194. return this;
  28195. };
  28196. /**
  28197. * Creates a ray that can be used to pick in the scene
  28198. * @param x defines the x coordinate of the origin (on-screen)
  28199. * @param y defines the y coordinate of the origin (on-screen)
  28200. * @param camera defines the camera to use for the picking
  28201. * @returns a Ray
  28202. */
  28203. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28204. var result = BABYLON.Ray.Zero();
  28205. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28206. return result;
  28207. };
  28208. /**
  28209. * Creates a ray that can be used to pick in the scene
  28210. * @param x defines the x coordinate of the origin (on-screen)
  28211. * @param y defines the y coordinate of the origin (on-screen)
  28212. * @param result defines the ray where to store the picking ray
  28213. * @param camera defines the camera to use for the picking
  28214. * @returns the current scene
  28215. */
  28216. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28217. if (!BABYLON.PickingInfo) {
  28218. return this;
  28219. }
  28220. var engine = this._engine;
  28221. if (!camera) {
  28222. if (!this.activeCamera)
  28223. throw new Error("Active camera not set");
  28224. camera = this.activeCamera;
  28225. }
  28226. var cameraViewport = camera.viewport;
  28227. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28228. var identity = BABYLON.Matrix.Identity();
  28229. // Moving coordinates to local viewport world
  28230. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28231. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28232. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28233. return this;
  28234. };
  28235. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28236. if (!BABYLON.PickingInfo) {
  28237. return null;
  28238. }
  28239. var pickingInfo = null;
  28240. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28241. var mesh = this.meshes[meshIndex];
  28242. if (predicate) {
  28243. if (!predicate(mesh)) {
  28244. continue;
  28245. }
  28246. }
  28247. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28248. continue;
  28249. }
  28250. var world = mesh.getWorldMatrix();
  28251. var ray = rayFunction(world);
  28252. var result = mesh.intersects(ray, fastCheck);
  28253. if (!result || !result.hit)
  28254. continue;
  28255. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28256. continue;
  28257. pickingInfo = result;
  28258. if (fastCheck) {
  28259. break;
  28260. }
  28261. }
  28262. return pickingInfo || new BABYLON.PickingInfo();
  28263. };
  28264. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28265. if (!BABYLON.PickingInfo) {
  28266. return null;
  28267. }
  28268. var pickingInfos = new Array();
  28269. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28270. var mesh = this.meshes[meshIndex];
  28271. if (predicate) {
  28272. if (!predicate(mesh)) {
  28273. continue;
  28274. }
  28275. }
  28276. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28277. continue;
  28278. }
  28279. var world = mesh.getWorldMatrix();
  28280. var ray = rayFunction(world);
  28281. var result = mesh.intersects(ray, false);
  28282. if (!result || !result.hit)
  28283. continue;
  28284. pickingInfos.push(result);
  28285. }
  28286. return pickingInfos;
  28287. };
  28288. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28289. if (!BABYLON.PickingInfo) {
  28290. return null;
  28291. }
  28292. var pickingInfo = null;
  28293. if (!camera) {
  28294. if (!this.activeCamera) {
  28295. return null;
  28296. }
  28297. camera = this.activeCamera;
  28298. }
  28299. if (this.spriteManagers.length > 0) {
  28300. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28301. var spriteManager = this.spriteManagers[spriteIndex];
  28302. if (!spriteManager.isPickable) {
  28303. continue;
  28304. }
  28305. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28306. if (!result || !result.hit)
  28307. continue;
  28308. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28309. continue;
  28310. pickingInfo = result;
  28311. if (fastCheck) {
  28312. break;
  28313. }
  28314. }
  28315. }
  28316. return pickingInfo || new BABYLON.PickingInfo();
  28317. };
  28318. /** Launch a ray to try to pick a mesh in the scene
  28319. * @param x position on screen
  28320. * @param y position on screen
  28321. * @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
  28322. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28323. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28324. * @returns a PickingInfo
  28325. */
  28326. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28327. var _this = this;
  28328. if (!BABYLON.PickingInfo) {
  28329. return null;
  28330. }
  28331. var result = this._internalPick(function (world) {
  28332. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28333. return _this._tempPickingRay;
  28334. }, predicate, fastCheck);
  28335. if (result) {
  28336. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28337. }
  28338. return result;
  28339. };
  28340. /** Launch a ray to try to pick a sprite in the scene
  28341. * @param x position on screen
  28342. * @param y position on screen
  28343. * @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
  28344. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28345. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28346. * @returns a PickingInfo
  28347. */
  28348. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28349. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28350. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28351. };
  28352. /** Use the given ray to pick a mesh in the scene
  28353. * @param ray The ray to use to pick meshes
  28354. * @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
  28355. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28356. * @returns a PickingInfo
  28357. */
  28358. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28359. var _this = this;
  28360. var result = this._internalPick(function (world) {
  28361. if (!_this._pickWithRayInverseMatrix) {
  28362. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28363. }
  28364. world.invertToRef(_this._pickWithRayInverseMatrix);
  28365. if (!_this._cachedRayForTransform) {
  28366. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28367. }
  28368. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28369. return _this._cachedRayForTransform;
  28370. }, predicate, fastCheck);
  28371. if (result) {
  28372. result.ray = ray;
  28373. }
  28374. return result;
  28375. };
  28376. /**
  28377. * Launch a ray to try to pick a mesh in the scene
  28378. * @param x X position on screen
  28379. * @param y Y position on screen
  28380. * @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
  28381. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28382. * @returns an array of PickingInfo
  28383. */
  28384. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28385. var _this = this;
  28386. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28387. };
  28388. /**
  28389. * Launch a ray to try to pick a mesh in the scene
  28390. * @param ray Ray to use
  28391. * @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
  28392. * @returns an array of PickingInfo
  28393. */
  28394. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28395. var _this = this;
  28396. return this._internalMultiPick(function (world) {
  28397. if (!_this._pickWithRayInverseMatrix) {
  28398. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28399. }
  28400. world.invertToRef(_this._pickWithRayInverseMatrix);
  28401. if (!_this._cachedRayForTransform) {
  28402. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28403. }
  28404. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28405. return _this._cachedRayForTransform;
  28406. }, predicate);
  28407. };
  28408. /**
  28409. * Force the value of meshUnderPointer
  28410. * @param mesh defines the mesh to use
  28411. */
  28412. Scene.prototype.setPointerOverMesh = function (mesh) {
  28413. if (this._pointerOverMesh === mesh) {
  28414. return;
  28415. }
  28416. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28417. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28418. }
  28419. this._pointerOverMesh = mesh;
  28420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28422. }
  28423. };
  28424. /**
  28425. * Gets the mesh under the pointer
  28426. * @returns a Mesh or null if no mesh is under the pointer
  28427. */
  28428. Scene.prototype.getPointerOverMesh = function () {
  28429. return this._pointerOverMesh;
  28430. };
  28431. /**
  28432. * Force the sprite under the pointer
  28433. * @param sprite defines the sprite to use
  28434. */
  28435. Scene.prototype.setPointerOverSprite = function (sprite) {
  28436. if (this._pointerOverSprite === sprite) {
  28437. return;
  28438. }
  28439. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28440. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28441. }
  28442. this._pointerOverSprite = sprite;
  28443. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28444. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28445. }
  28446. };
  28447. /**
  28448. * Gets the sprite under the pointer
  28449. * @returns a Sprite or null if no sprite is under the pointer
  28450. */
  28451. Scene.prototype.getPointerOverSprite = function () {
  28452. return this._pointerOverSprite;
  28453. };
  28454. // Physics
  28455. /**
  28456. * Gets the current physics engine
  28457. * @returns a PhysicsEngine or null if none attached
  28458. */
  28459. Scene.prototype.getPhysicsEngine = function () {
  28460. return this._physicsEngine;
  28461. };
  28462. /**
  28463. * Enables physics to the current scene
  28464. * @param gravity defines the scene's gravity for the physics engine
  28465. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28466. * @return a boolean indicating if the physics engine was initialized
  28467. */
  28468. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28469. if (gravity === void 0) { gravity = null; }
  28470. if (this._physicsEngine) {
  28471. return true;
  28472. }
  28473. try {
  28474. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28475. return true;
  28476. }
  28477. catch (e) {
  28478. BABYLON.Tools.Error(e.message);
  28479. return false;
  28480. }
  28481. };
  28482. /**
  28483. * Disables and disposes the physics engine associated with the scene
  28484. */
  28485. Scene.prototype.disablePhysicsEngine = function () {
  28486. if (!this._physicsEngine) {
  28487. return;
  28488. }
  28489. this._physicsEngine.dispose();
  28490. this._physicsEngine = null;
  28491. };
  28492. /**
  28493. * Gets a boolean indicating if there is an active physics engine
  28494. * @returns a boolean indicating if there is an active physics engine
  28495. */
  28496. Scene.prototype.isPhysicsEnabled = function () {
  28497. return this._physicsEngine !== undefined;
  28498. };
  28499. /**
  28500. * Deletes a physics compound impostor
  28501. * @param compound defines the compound to delete
  28502. */
  28503. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28504. var mesh = compound.parts[0].mesh;
  28505. if (mesh.physicsImpostor) {
  28506. mesh.physicsImpostor.dispose( /*true*/);
  28507. mesh.physicsImpostor = null;
  28508. }
  28509. };
  28510. // Misc.
  28511. /** @hidden */
  28512. Scene.prototype._rebuildGeometries = function () {
  28513. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28514. var geometry = _a[_i];
  28515. geometry._rebuild();
  28516. }
  28517. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28518. var mesh = _c[_b];
  28519. mesh._rebuild();
  28520. }
  28521. if (this.postProcessManager) {
  28522. this.postProcessManager._rebuild();
  28523. }
  28524. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28525. var component = _e[_d];
  28526. component.rebuild();
  28527. }
  28528. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28529. var system = _g[_f];
  28530. system.rebuild();
  28531. }
  28532. if (this._postProcessRenderPipelineManager) {
  28533. this._postProcessRenderPipelineManager._rebuild();
  28534. }
  28535. };
  28536. /** @hidden */
  28537. Scene.prototype._rebuildTextures = function () {
  28538. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28539. var texture = _a[_i];
  28540. texture._rebuild();
  28541. }
  28542. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28543. };
  28544. /**
  28545. * Creates a default light for the scene.
  28546. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28547. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28548. */
  28549. Scene.prototype.createDefaultLight = function (replace) {
  28550. if (replace === void 0) { replace = false; }
  28551. // Dispose existing light in replace mode.
  28552. if (replace) {
  28553. if (this.lights) {
  28554. for (var i = 0; i < this.lights.length; i++) {
  28555. this.lights[i].dispose();
  28556. }
  28557. }
  28558. }
  28559. // Light
  28560. if (this.lights.length === 0) {
  28561. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28562. }
  28563. };
  28564. /**
  28565. * Creates a default camera for the scene.
  28566. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28567. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28568. * @param replace has default false, when true replaces the active camera in the scene
  28569. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28570. */
  28571. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28572. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28573. if (replace === void 0) { replace = false; }
  28574. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28575. // Dispose existing camera in replace mode.
  28576. if (replace) {
  28577. if (this.activeCamera) {
  28578. this.activeCamera.dispose();
  28579. this.activeCamera = null;
  28580. }
  28581. }
  28582. // Camera
  28583. if (!this.activeCamera) {
  28584. var worldExtends = this.getWorldExtends();
  28585. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28586. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28587. var camera;
  28588. var radius = worldSize.length() * 1.5;
  28589. // empty scene scenario!
  28590. if (!isFinite(radius)) {
  28591. radius = 1;
  28592. worldCenter.copyFromFloats(0, 0, 0);
  28593. }
  28594. if (createArcRotateCamera) {
  28595. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28596. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28597. arcRotateCamera.wheelPrecision = 100 / radius;
  28598. camera = arcRotateCamera;
  28599. }
  28600. else {
  28601. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28602. freeCamera.setTarget(worldCenter);
  28603. camera = freeCamera;
  28604. }
  28605. camera.minZ = radius * 0.01;
  28606. camera.maxZ = radius * 1000;
  28607. camera.speed = radius * 0.2;
  28608. this.activeCamera = camera;
  28609. var canvas = this.getEngine().getRenderingCanvas();
  28610. if (attachCameraControls && canvas) {
  28611. camera.attachControl(canvas);
  28612. }
  28613. }
  28614. };
  28615. /**
  28616. * Creates a default camera and a default light.
  28617. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28618. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28619. * @param replace has the default false, when true replaces the active camera/light in the scene
  28620. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28621. */
  28622. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28623. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28624. if (replace === void 0) { replace = false; }
  28625. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28626. this.createDefaultLight(replace);
  28627. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28628. };
  28629. /**
  28630. * Creates a new sky box
  28631. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28632. * @param environmentTexture defines the texture to use as environment texture
  28633. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28634. * @param scale defines the overall scale of the skybox
  28635. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28636. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28637. * @returns a new mesh holding the sky box
  28638. */
  28639. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28640. if (pbr === void 0) { pbr = false; }
  28641. if (scale === void 0) { scale = 1000; }
  28642. if (blur === void 0) { blur = 0; }
  28643. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28644. if (!environmentTexture) {
  28645. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28646. return null;
  28647. }
  28648. if (setGlobalEnvTexture) {
  28649. if (environmentTexture) {
  28650. this.environmentTexture = environmentTexture;
  28651. }
  28652. }
  28653. // Skybox
  28654. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28655. if (pbr) {
  28656. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28657. hdrSkyboxMaterial.backFaceCulling = false;
  28658. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28659. if (hdrSkyboxMaterial.reflectionTexture) {
  28660. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28661. }
  28662. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28663. hdrSkyboxMaterial.disableLighting = true;
  28664. hdrSkyboxMaterial.twoSidedLighting = true;
  28665. hdrSkybox.infiniteDistance = true;
  28666. hdrSkybox.material = hdrSkyboxMaterial;
  28667. }
  28668. else {
  28669. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28670. skyboxMaterial.backFaceCulling = false;
  28671. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28672. if (skyboxMaterial.reflectionTexture) {
  28673. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28674. }
  28675. skyboxMaterial.disableLighting = true;
  28676. hdrSkybox.infiniteDistance = true;
  28677. hdrSkybox.material = skyboxMaterial;
  28678. }
  28679. return hdrSkybox;
  28680. };
  28681. /**
  28682. * Creates a new environment
  28683. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28684. * @param options defines the options you can use to configure the environment
  28685. * @returns the new EnvironmentHelper
  28686. */
  28687. Scene.prototype.createDefaultEnvironment = function (options) {
  28688. if (BABYLON.EnvironmentHelper) {
  28689. return new BABYLON.EnvironmentHelper(options, this);
  28690. }
  28691. return null;
  28692. };
  28693. /**
  28694. * Creates a new VREXperienceHelper
  28695. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28696. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28697. * @returns a new VREXperienceHelper
  28698. */
  28699. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28700. if (webVROptions === void 0) { webVROptions = {}; }
  28701. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28702. };
  28703. // Tags
  28704. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28705. if (tagsQuery === undefined) {
  28706. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28707. return list;
  28708. }
  28709. var listByTags = [];
  28710. forEach = forEach || (function (item) { return; });
  28711. for (var i in list) {
  28712. var item = list[i];
  28713. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28714. listByTags.push(item);
  28715. forEach(item);
  28716. }
  28717. }
  28718. return listByTags;
  28719. };
  28720. /**
  28721. * Get a list of meshes by tags
  28722. * @param tagsQuery defines the tags query to use
  28723. * @param forEach defines a predicate used to filter results
  28724. * @returns an array of Mesh
  28725. */
  28726. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28727. return this._getByTags(this.meshes, tagsQuery, forEach);
  28728. };
  28729. /**
  28730. * Get a list of cameras by tags
  28731. * @param tagsQuery defines the tags query to use
  28732. * @param forEach defines a predicate used to filter results
  28733. * @returns an array of Camera
  28734. */
  28735. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28736. return this._getByTags(this.cameras, tagsQuery, forEach);
  28737. };
  28738. /**
  28739. * Get a list of lights by tags
  28740. * @param tagsQuery defines the tags query to use
  28741. * @param forEach defines a predicate used to filter results
  28742. * @returns an array of Light
  28743. */
  28744. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28745. return this._getByTags(this.lights, tagsQuery, forEach);
  28746. };
  28747. /**
  28748. * Get a list of materials by tags
  28749. * @param tagsQuery defines the tags query to use
  28750. * @param forEach defines a predicate used to filter results
  28751. * @returns an array of Material
  28752. */
  28753. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28754. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28755. };
  28756. /**
  28757. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28758. * This allowed control for front to back rendering or reversly depending of the special needs.
  28759. *
  28760. * @param renderingGroupId The rendering group id corresponding to its index
  28761. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28762. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28763. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28764. */
  28765. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28766. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28767. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28768. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28769. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28770. };
  28771. /**
  28772. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28773. *
  28774. * @param renderingGroupId The rendering group id corresponding to its index
  28775. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28776. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28777. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28778. */
  28779. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28780. if (depth === void 0) { depth = true; }
  28781. if (stencil === void 0) { stencil = true; }
  28782. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28783. };
  28784. /**
  28785. * Will flag all materials as dirty to trigger new shader compilation
  28786. * @param flag defines the flag used to specify which material part must be marked as dirty
  28787. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28788. */
  28789. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28790. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28791. var material = _a[_i];
  28792. if (predicate && !predicate(material)) {
  28793. continue;
  28794. }
  28795. material.markAsDirty(flag);
  28796. }
  28797. };
  28798. /** @hidden */
  28799. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28800. var _this = this;
  28801. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28802. this._activeRequests.push(request);
  28803. request.onCompleteObservable.add(function (request) {
  28804. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28805. });
  28806. return request;
  28807. };
  28808. /** @hidden */
  28809. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28810. var _this = this;
  28811. return new Promise(function (resolve, reject) {
  28812. _this._loadFile(url, function (data) {
  28813. resolve(data);
  28814. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28815. reject(exception);
  28816. });
  28817. });
  28818. };
  28819. // Statics
  28820. Scene._FOGMODE_NONE = 0;
  28821. Scene._FOGMODE_EXP = 1;
  28822. Scene._FOGMODE_EXP2 = 2;
  28823. Scene._FOGMODE_LINEAR = 3;
  28824. Scene._uniqueIdCounter = 0;
  28825. /**
  28826. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28827. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28828. */
  28829. Scene.MinDeltaTime = 1.0;
  28830. /**
  28831. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28832. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28833. */
  28834. Scene.MaxDeltaTime = 1000.0;
  28835. /** The distance in pixel that you have to move to prevent some events */
  28836. Scene.DragMovementThreshold = 10; // in pixels
  28837. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28838. Scene.LongPressDelay = 500; // in milliseconds
  28839. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28840. Scene.DoubleClickDelay = 300; // in milliseconds
  28841. /** If you need to check double click without raising a single click at first click, enable this flag */
  28842. Scene.ExclusiveDoubleClickMode = false;
  28843. return Scene;
  28844. }(BABYLON.AbstractScene));
  28845. BABYLON.Scene = Scene;
  28846. })(BABYLON || (BABYLON = {}));
  28847. //# sourceMappingURL=babylon.scene.js.map
  28848. var BABYLON;
  28849. (function (BABYLON) {
  28850. /**
  28851. * Set of assets to keep when moving a scene into an asset container.
  28852. */
  28853. var KeepAssets = /** @class */ (function (_super) {
  28854. __extends(KeepAssets, _super);
  28855. function KeepAssets() {
  28856. return _super !== null && _super.apply(this, arguments) || this;
  28857. }
  28858. return KeepAssets;
  28859. }(BABYLON.AbstractScene));
  28860. BABYLON.KeepAssets = KeepAssets;
  28861. /**
  28862. * Container with a set of assets that can be added or removed from a scene.
  28863. */
  28864. var AssetContainer = /** @class */ (function (_super) {
  28865. __extends(AssetContainer, _super);
  28866. /**
  28867. * Instantiates an AssetContainer.
  28868. * @param scene The scene the AssetContainer belongs to.
  28869. */
  28870. function AssetContainer(scene) {
  28871. var _this = _super.call(this) || this;
  28872. _this.scene = scene;
  28873. return _this;
  28874. }
  28875. /**
  28876. * Adds all the assets from the container to the scene.
  28877. */
  28878. AssetContainer.prototype.addAllToScene = function () {
  28879. var _this = this;
  28880. this.cameras.forEach(function (o) {
  28881. _this.scene.addCamera(o);
  28882. });
  28883. this.lights.forEach(function (o) {
  28884. _this.scene.addLight(o);
  28885. });
  28886. this.meshes.forEach(function (o) {
  28887. _this.scene.addMesh(o);
  28888. });
  28889. this.skeletons.forEach(function (o) {
  28890. _this.scene.addSkeleton(o);
  28891. });
  28892. this.animations.forEach(function (o) {
  28893. _this.scene.addAnimation(o);
  28894. });
  28895. this.animationGroups.forEach(function (o) {
  28896. _this.scene.addAnimationGroup(o);
  28897. });
  28898. this.multiMaterials.forEach(function (o) {
  28899. _this.scene.addMultiMaterial(o);
  28900. });
  28901. this.materials.forEach(function (o) {
  28902. _this.scene.addMaterial(o);
  28903. });
  28904. this.morphTargetManagers.forEach(function (o) {
  28905. _this.scene.addMorphTargetManager(o);
  28906. });
  28907. this.geometries.forEach(function (o) {
  28908. _this.scene.addGeometry(o);
  28909. });
  28910. this.transformNodes.forEach(function (o) {
  28911. _this.scene.addTransformNode(o);
  28912. });
  28913. this.actionManagers.forEach(function (o) {
  28914. _this.scene.addActionManager(o);
  28915. });
  28916. this.sounds.forEach(function (o) {
  28917. o.play();
  28918. o.autoplay = true;
  28919. _this.scene.mainSoundTrack.AddSound(o);
  28920. });
  28921. this.textures.forEach(function (o) {
  28922. _this.scene.addTexture(o);
  28923. });
  28924. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28925. var component = _a[_i];
  28926. component.addFromContainer(this.scene);
  28927. }
  28928. };
  28929. /**
  28930. * Removes all the assets in the container from the scene
  28931. */
  28932. AssetContainer.prototype.removeAllFromScene = function () {
  28933. var _this = this;
  28934. this.cameras.forEach(function (o) {
  28935. _this.scene.removeCamera(o);
  28936. });
  28937. this.lights.forEach(function (o) {
  28938. _this.scene.removeLight(o);
  28939. });
  28940. this.meshes.forEach(function (o) {
  28941. _this.scene.removeMesh(o);
  28942. });
  28943. this.skeletons.forEach(function (o) {
  28944. _this.scene.removeSkeleton(o);
  28945. });
  28946. this.animations.forEach(function (o) {
  28947. _this.scene.removeAnimation(o);
  28948. });
  28949. this.animationGroups.forEach(function (o) {
  28950. _this.scene.removeAnimationGroup(o);
  28951. });
  28952. this.multiMaterials.forEach(function (o) {
  28953. _this.scene.removeMultiMaterial(o);
  28954. });
  28955. this.materials.forEach(function (o) {
  28956. _this.scene.removeMaterial(o);
  28957. });
  28958. this.morphTargetManagers.forEach(function (o) {
  28959. _this.scene.removeMorphTargetManager(o);
  28960. });
  28961. this.geometries.forEach(function (o) {
  28962. _this.scene.removeGeometry(o);
  28963. });
  28964. this.transformNodes.forEach(function (o) {
  28965. _this.scene.removeTransformNode(o);
  28966. });
  28967. this.actionManagers.forEach(function (o) {
  28968. _this.scene.removeActionManager(o);
  28969. });
  28970. this.sounds.forEach(function (o) {
  28971. o.stop();
  28972. o.autoplay = false;
  28973. _this.scene.mainSoundTrack.RemoveSound(o);
  28974. });
  28975. this.textures.forEach(function (o) {
  28976. _this.scene.removeTexture(o);
  28977. });
  28978. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28979. var component = _a[_i];
  28980. component.removeFromContainer(this.scene);
  28981. }
  28982. };
  28983. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28984. if (!sourceAssets) {
  28985. return;
  28986. }
  28987. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28988. var asset = sourceAssets_1[_i];
  28989. var move = true;
  28990. if (keepAssets) {
  28991. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28992. var keepAsset = keepAssets_1[_a];
  28993. if (asset === keepAsset) {
  28994. move = false;
  28995. break;
  28996. }
  28997. }
  28998. }
  28999. if (move) {
  29000. targetAssets.push(asset);
  29001. }
  29002. }
  29003. };
  29004. /**
  29005. * Removes all the assets contained in the scene and adds them to the container.
  29006. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29007. */
  29008. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29009. if (keepAssets === undefined) {
  29010. keepAssets = new KeepAssets();
  29011. }
  29012. for (var key in this) {
  29013. if (this.hasOwnProperty(key)) {
  29014. this[key] = this[key] || [];
  29015. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29016. }
  29017. }
  29018. this.removeAllFromScene();
  29019. };
  29020. /**
  29021. * 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.
  29022. * @returns the root mesh
  29023. */
  29024. AssetContainer.prototype.createRootMesh = function () {
  29025. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29026. this.meshes.forEach(function (m) {
  29027. if (!m.parent) {
  29028. rootMesh.addChild(m);
  29029. }
  29030. });
  29031. this.meshes.unshift(rootMesh);
  29032. return rootMesh;
  29033. };
  29034. return AssetContainer;
  29035. }(BABYLON.AbstractScene));
  29036. BABYLON.AssetContainer = AssetContainer;
  29037. })(BABYLON || (BABYLON = {}));
  29038. //# sourceMappingURL=babylon.assetContainer.js.map
  29039. var BABYLON;
  29040. (function (BABYLON) {
  29041. var Buffer = /** @class */ (function () {
  29042. /**
  29043. * Constructor
  29044. * @param engine the engine
  29045. * @param data the data to use for this buffer
  29046. * @param updatable whether the data is updatable
  29047. * @param stride the stride (optional)
  29048. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29049. * @param instanced whether the buffer is instanced (optional)
  29050. * @param useBytes set to true if the stride in in bytes (optional)
  29051. */
  29052. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29053. if (stride === void 0) { stride = 0; }
  29054. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29055. if (instanced === void 0) { instanced = false; }
  29056. if (useBytes === void 0) { useBytes = false; }
  29057. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29058. this._engine = engine.getScene().getEngine();
  29059. }
  29060. else {
  29061. this._engine = engine;
  29062. }
  29063. this._updatable = updatable;
  29064. this._instanced = instanced;
  29065. this._data = data;
  29066. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29067. if (!postponeInternalCreation) { // by default
  29068. this.create();
  29069. }
  29070. }
  29071. /**
  29072. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29073. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29074. * @param offset defines offset in the buffer (0 by default)
  29075. * @param size defines the size in floats of attributes (position is 3 for instance)
  29076. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29077. * @param instanced defines if the vertex buffer contains indexed data
  29078. * @param useBytes defines if the offset and stride are in bytes
  29079. * @returns the new vertex buffer
  29080. */
  29081. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29082. if (useBytes === void 0) { useBytes = false; }
  29083. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29084. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29085. // a lot of these parameters are ignored as they are overriden by the buffer
  29086. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29087. };
  29088. // Properties
  29089. Buffer.prototype.isUpdatable = function () {
  29090. return this._updatable;
  29091. };
  29092. Buffer.prototype.getData = function () {
  29093. return this._data;
  29094. };
  29095. Buffer.prototype.getBuffer = function () {
  29096. return this._buffer;
  29097. };
  29098. /**
  29099. * Gets the stride in float32 units (i.e. byte stride / 4).
  29100. * May not be an integer if the byte stride is not divisible by 4.
  29101. * DEPRECATED. Use byteStride instead.
  29102. * @returns the stride in float32 units
  29103. */
  29104. Buffer.prototype.getStrideSize = function () {
  29105. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29106. };
  29107. // Methods
  29108. Buffer.prototype.create = function (data) {
  29109. if (data === void 0) { data = null; }
  29110. if (!data && this._buffer) {
  29111. return; // nothing to do
  29112. }
  29113. data = data || this._data;
  29114. if (!data) {
  29115. return;
  29116. }
  29117. if (!this._buffer) { // create buffer
  29118. if (this._updatable) {
  29119. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29120. this._data = data;
  29121. }
  29122. else {
  29123. this._buffer = this._engine.createVertexBuffer(data);
  29124. }
  29125. }
  29126. else if (this._updatable) { // update buffer
  29127. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29128. this._data = data;
  29129. }
  29130. };
  29131. Buffer.prototype._rebuild = function () {
  29132. this._buffer = null;
  29133. this.create(this._data);
  29134. };
  29135. Buffer.prototype.update = function (data) {
  29136. this.create(data);
  29137. };
  29138. /**
  29139. * Updates the data directly.
  29140. * @param data the new data
  29141. * @param offset the new offset
  29142. * @param vertexCount the vertex count (optional)
  29143. * @param useBytes set to true if the offset is in bytes
  29144. */
  29145. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29146. if (useBytes === void 0) { useBytes = false; }
  29147. if (!this._buffer) {
  29148. return;
  29149. }
  29150. if (this._updatable) { // update buffer
  29151. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29152. this._data = null;
  29153. }
  29154. };
  29155. Buffer.prototype.dispose = function () {
  29156. if (!this._buffer) {
  29157. return;
  29158. }
  29159. if (this._engine._releaseBuffer(this._buffer)) {
  29160. this._buffer = null;
  29161. }
  29162. };
  29163. return Buffer;
  29164. }());
  29165. BABYLON.Buffer = Buffer;
  29166. })(BABYLON || (BABYLON = {}));
  29167. //# sourceMappingURL=babylon.buffer.js.map
  29168. var BABYLON;
  29169. (function (BABYLON) {
  29170. var VertexBuffer = /** @class */ (function () {
  29171. /**
  29172. * Constructor
  29173. * @param engine the engine
  29174. * @param data the data to use for this vertex buffer
  29175. * @param kind the vertex buffer kind
  29176. * @param updatable whether the data is updatable
  29177. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29178. * @param stride the stride (optional)
  29179. * @param instanced whether the buffer is instanced (optional)
  29180. * @param offset the offset of the data (optional)
  29181. * @param size the number of components (optional)
  29182. * @param type the type of the component (optional)
  29183. * @param normalized whether the data contains normalized data (optional)
  29184. * @param useBytes set to true if stride and offset are in bytes (optional)
  29185. */
  29186. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29187. if (normalized === void 0) { normalized = false; }
  29188. if (useBytes === void 0) { useBytes = false; }
  29189. if (data instanceof BABYLON.Buffer) {
  29190. this._buffer = data;
  29191. this._ownsBuffer = false;
  29192. }
  29193. else {
  29194. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29195. this._ownsBuffer = true;
  29196. }
  29197. this._kind = kind;
  29198. if (type == undefined) {
  29199. var data_1 = this.getData();
  29200. this.type = VertexBuffer.FLOAT;
  29201. if (data_1 instanceof Int8Array)
  29202. this.type = VertexBuffer.BYTE;
  29203. else if (data_1 instanceof Uint8Array)
  29204. this.type = VertexBuffer.UNSIGNED_BYTE;
  29205. else if (data_1 instanceof Int16Array)
  29206. this.type = VertexBuffer.SHORT;
  29207. else if (data_1 instanceof Uint16Array)
  29208. this.type = VertexBuffer.UNSIGNED_SHORT;
  29209. else if (data_1 instanceof Int32Array)
  29210. this.type = VertexBuffer.INT;
  29211. else if (data_1 instanceof Uint32Array)
  29212. this.type = VertexBuffer.UNSIGNED_INT;
  29213. }
  29214. else {
  29215. this.type = type;
  29216. }
  29217. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29218. if (useBytes) {
  29219. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29220. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29221. this.byteOffset = offset || 0;
  29222. }
  29223. else {
  29224. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29225. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29226. this.byteOffset = (offset || 0) * typeByteLength;
  29227. }
  29228. this.normalized = normalized;
  29229. this._instanced = instanced !== undefined ? instanced : false;
  29230. this._instanceDivisor = instanced ? 1 : 0;
  29231. }
  29232. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29233. /**
  29234. * Gets or sets the instance divisor when in instanced mode
  29235. */
  29236. get: function () {
  29237. return this._instanceDivisor;
  29238. },
  29239. set: function (value) {
  29240. this._instanceDivisor = value;
  29241. if (value == 0) {
  29242. this._instanced = false;
  29243. }
  29244. else {
  29245. this._instanced = true;
  29246. }
  29247. },
  29248. enumerable: true,
  29249. configurable: true
  29250. });
  29251. VertexBuffer.prototype._rebuild = function () {
  29252. if (!this._buffer) {
  29253. return;
  29254. }
  29255. this._buffer._rebuild();
  29256. };
  29257. /**
  29258. * Returns the kind of the VertexBuffer (string).
  29259. */
  29260. VertexBuffer.prototype.getKind = function () {
  29261. return this._kind;
  29262. };
  29263. // Properties
  29264. /**
  29265. * Boolean : is the VertexBuffer updatable ?
  29266. */
  29267. VertexBuffer.prototype.isUpdatable = function () {
  29268. return this._buffer.isUpdatable();
  29269. };
  29270. /**
  29271. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29272. */
  29273. VertexBuffer.prototype.getData = function () {
  29274. return this._buffer.getData();
  29275. };
  29276. /**
  29277. * Returns the WebGLBuffer associated to the VertexBuffer.
  29278. */
  29279. VertexBuffer.prototype.getBuffer = function () {
  29280. return this._buffer.getBuffer();
  29281. };
  29282. /**
  29283. * Returns the stride as a multiple of the type byte length.
  29284. * DEPRECATED. Use byteStride instead.
  29285. */
  29286. VertexBuffer.prototype.getStrideSize = function () {
  29287. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29288. };
  29289. /**
  29290. * Returns the offset as a multiple of the type byte length.
  29291. * DEPRECATED. Use byteOffset instead.
  29292. */
  29293. VertexBuffer.prototype.getOffset = function () {
  29294. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29295. };
  29296. /**
  29297. * Returns the number of components per vertex attribute (integer).
  29298. */
  29299. VertexBuffer.prototype.getSize = function () {
  29300. return this._size;
  29301. };
  29302. /**
  29303. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29304. */
  29305. VertexBuffer.prototype.getIsInstanced = function () {
  29306. return this._instanced;
  29307. };
  29308. /**
  29309. * Returns the instancing divisor, zero for non-instanced (integer).
  29310. */
  29311. VertexBuffer.prototype.getInstanceDivisor = function () {
  29312. return this._instanceDivisor;
  29313. };
  29314. // Methods
  29315. /**
  29316. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29317. * Returns the created WebGLBuffer.
  29318. */
  29319. VertexBuffer.prototype.create = function (data) {
  29320. return this._buffer.create(data);
  29321. };
  29322. /**
  29323. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29324. * This function will create a new buffer if the current one is not updatable
  29325. * Returns the updated WebGLBuffer.
  29326. */
  29327. VertexBuffer.prototype.update = function (data) {
  29328. return this._buffer.update(data);
  29329. };
  29330. /**
  29331. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29332. * Returns the directly updated WebGLBuffer.
  29333. * @param data the new data
  29334. * @param offset the new offset
  29335. * @param useBytes set to true if the offset is in bytes
  29336. */
  29337. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29338. if (useBytes === void 0) { useBytes = false; }
  29339. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29340. };
  29341. /**
  29342. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29343. */
  29344. VertexBuffer.prototype.dispose = function () {
  29345. if (this._ownsBuffer) {
  29346. this._buffer.dispose();
  29347. }
  29348. };
  29349. /**
  29350. * Enumerates each value of this vertex buffer as numbers.
  29351. * @param count the number of values to enumerate
  29352. * @param callback the callback function called for each value
  29353. */
  29354. VertexBuffer.prototype.forEach = function (count, callback) {
  29355. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29356. };
  29357. Object.defineProperty(VertexBuffer, "PositionKind", {
  29358. get: function () {
  29359. return VertexBuffer._PositionKind;
  29360. },
  29361. enumerable: true,
  29362. configurable: true
  29363. });
  29364. Object.defineProperty(VertexBuffer, "NormalKind", {
  29365. get: function () {
  29366. return VertexBuffer._NormalKind;
  29367. },
  29368. enumerable: true,
  29369. configurable: true
  29370. });
  29371. Object.defineProperty(VertexBuffer, "TangentKind", {
  29372. get: function () {
  29373. return VertexBuffer._TangentKind;
  29374. },
  29375. enumerable: true,
  29376. configurable: true
  29377. });
  29378. Object.defineProperty(VertexBuffer, "UVKind", {
  29379. get: function () {
  29380. return VertexBuffer._UVKind;
  29381. },
  29382. enumerable: true,
  29383. configurable: true
  29384. });
  29385. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29386. get: function () {
  29387. return VertexBuffer._UV2Kind;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29393. get: function () {
  29394. return VertexBuffer._UV3Kind;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29400. get: function () {
  29401. return VertexBuffer._UV4Kind;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29407. get: function () {
  29408. return VertexBuffer._UV5Kind;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29414. get: function () {
  29415. return VertexBuffer._UV6Kind;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(VertexBuffer, "ColorKind", {
  29421. get: function () {
  29422. return VertexBuffer._ColorKind;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29428. get: function () {
  29429. return VertexBuffer._MatricesIndicesKind;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29435. get: function () {
  29436. return VertexBuffer._MatricesWeightsKind;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29442. get: function () {
  29443. return VertexBuffer._MatricesIndicesExtraKind;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29449. get: function () {
  29450. return VertexBuffer._MatricesWeightsExtraKind;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. /**
  29456. * Deduces the stride given a kind.
  29457. * @param kind The kind string to deduce
  29458. * @returns The deduced stride
  29459. */
  29460. VertexBuffer.DeduceStride = function (kind) {
  29461. switch (kind) {
  29462. case VertexBuffer.UVKind:
  29463. case VertexBuffer.UV2Kind:
  29464. case VertexBuffer.UV3Kind:
  29465. case VertexBuffer.UV4Kind:
  29466. case VertexBuffer.UV5Kind:
  29467. case VertexBuffer.UV6Kind:
  29468. return 2;
  29469. case VertexBuffer.NormalKind:
  29470. case VertexBuffer.PositionKind:
  29471. return 3;
  29472. case VertexBuffer.ColorKind:
  29473. case VertexBuffer.MatricesIndicesKind:
  29474. case VertexBuffer.MatricesIndicesExtraKind:
  29475. case VertexBuffer.MatricesWeightsKind:
  29476. case VertexBuffer.MatricesWeightsExtraKind:
  29477. case VertexBuffer.TangentKind:
  29478. return 4;
  29479. default:
  29480. throw new Error("Invalid kind '" + kind + "'");
  29481. }
  29482. };
  29483. /**
  29484. * Gets the byte length of the given type.
  29485. * @param type the type
  29486. * @returns the number of bytes
  29487. */
  29488. VertexBuffer.GetTypeByteLength = function (type) {
  29489. switch (type) {
  29490. case VertexBuffer.BYTE:
  29491. case VertexBuffer.UNSIGNED_BYTE:
  29492. return 1;
  29493. case VertexBuffer.SHORT:
  29494. case VertexBuffer.UNSIGNED_SHORT:
  29495. return 2;
  29496. case VertexBuffer.INT:
  29497. case VertexBuffer.FLOAT:
  29498. return 4;
  29499. default:
  29500. throw new Error("Invalid type '" + type + "'");
  29501. }
  29502. };
  29503. /**
  29504. * Enumerates each value of the given parameters as numbers.
  29505. * @param data the data to enumerate
  29506. * @param byteOffset the byte offset of the data
  29507. * @param byteStride the byte stride of the data
  29508. * @param componentCount the number of components per element
  29509. * @param componentType the type of the component
  29510. * @param count the total number of components
  29511. * @param normalized whether the data is normalized
  29512. * @param callback the callback function called for each value
  29513. */
  29514. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29515. if (data instanceof Array) {
  29516. var offset = byteOffset / 4;
  29517. var stride = byteStride / 4;
  29518. for (var index = 0; index < count; index += componentCount) {
  29519. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29520. callback(data[offset + componentIndex], index + componentIndex);
  29521. }
  29522. offset += stride;
  29523. }
  29524. }
  29525. else {
  29526. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29527. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29528. for (var index = 0; index < count; index += componentCount) {
  29529. var componentByteOffset = byteOffset;
  29530. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29531. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29532. callback(value, index + componentIndex);
  29533. componentByteOffset += componentByteLength;
  29534. }
  29535. byteOffset += byteStride;
  29536. }
  29537. }
  29538. };
  29539. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29540. switch (type) {
  29541. case VertexBuffer.BYTE: {
  29542. var value = dataView.getInt8(byteOffset);
  29543. if (normalized) {
  29544. value = Math.max(value / 127, -1);
  29545. }
  29546. return value;
  29547. }
  29548. case VertexBuffer.UNSIGNED_BYTE: {
  29549. var value = dataView.getUint8(byteOffset);
  29550. if (normalized) {
  29551. value = value / 255;
  29552. }
  29553. return value;
  29554. }
  29555. case VertexBuffer.SHORT: {
  29556. var value = dataView.getInt16(byteOffset, true);
  29557. if (normalized) {
  29558. value = Math.max(value / 16383, -1);
  29559. }
  29560. return value;
  29561. }
  29562. case VertexBuffer.UNSIGNED_SHORT: {
  29563. var value = dataView.getUint16(byteOffset, true);
  29564. if (normalized) {
  29565. value = value / 65535;
  29566. }
  29567. return value;
  29568. }
  29569. case VertexBuffer.FLOAT: {
  29570. return dataView.getFloat32(byteOffset, true);
  29571. }
  29572. default: {
  29573. throw new Error("Invalid component type " + type);
  29574. }
  29575. }
  29576. };
  29577. /**
  29578. * The byte type.
  29579. */
  29580. VertexBuffer.BYTE = 5120;
  29581. /**
  29582. * The unsigned byte type.
  29583. */
  29584. VertexBuffer.UNSIGNED_BYTE = 5121;
  29585. /**
  29586. * The short type.
  29587. */
  29588. VertexBuffer.SHORT = 5122;
  29589. /**
  29590. * The unsigned short type.
  29591. */
  29592. VertexBuffer.UNSIGNED_SHORT = 5123;
  29593. /**
  29594. * The integer type.
  29595. */
  29596. VertexBuffer.INT = 5124;
  29597. /**
  29598. * The unsigned integer type.
  29599. */
  29600. VertexBuffer.UNSIGNED_INT = 5125;
  29601. /**
  29602. * The float type.
  29603. */
  29604. VertexBuffer.FLOAT = 5126;
  29605. // Enums
  29606. VertexBuffer._PositionKind = "position";
  29607. VertexBuffer._NormalKind = "normal";
  29608. VertexBuffer._TangentKind = "tangent";
  29609. VertexBuffer._UVKind = "uv";
  29610. VertexBuffer._UV2Kind = "uv2";
  29611. VertexBuffer._UV3Kind = "uv3";
  29612. VertexBuffer._UV4Kind = "uv4";
  29613. VertexBuffer._UV5Kind = "uv5";
  29614. VertexBuffer._UV6Kind = "uv6";
  29615. VertexBuffer._ColorKind = "color";
  29616. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29617. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29618. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29619. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29620. return VertexBuffer;
  29621. }());
  29622. BABYLON.VertexBuffer = VertexBuffer;
  29623. })(BABYLON || (BABYLON = {}));
  29624. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29625. var BABYLON;
  29626. (function (BABYLON) {
  29627. /**
  29628. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29629. */
  29630. var DummyInternalTextureTracker = /** @class */ (function () {
  29631. function DummyInternalTextureTracker() {
  29632. /**
  29633. * Gets or set the previous tracker in the list
  29634. */
  29635. this.previous = null;
  29636. /**
  29637. * Gets or set the next tracker in the list
  29638. */
  29639. this.next = null;
  29640. }
  29641. return DummyInternalTextureTracker;
  29642. }());
  29643. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29644. })(BABYLON || (BABYLON = {}));
  29645. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29646. var BABYLON;
  29647. (function (BABYLON) {
  29648. /**
  29649. * Class used to store data associated with WebGL texture data for the engine
  29650. * This class should not be used directly
  29651. */
  29652. var InternalTexture = /** @class */ (function () {
  29653. /**
  29654. * Creates a new InternalTexture
  29655. * @param engine defines the engine to use
  29656. * @param dataSource defines the type of data that will be used
  29657. */
  29658. function InternalTexture(engine, dataSource) {
  29659. /**
  29660. * Observable called when the texture is loaded
  29661. */
  29662. this.onLoadedObservable = new BABYLON.Observable();
  29663. /**
  29664. * Gets or set the previous tracker in the list
  29665. */
  29666. this.previous = null;
  29667. /**
  29668. * Gets or set the next tracker in the list
  29669. */
  29670. this.next = null;
  29671. // Private
  29672. /** @hidden */
  29673. this._initialSlot = -1;
  29674. /** @hidden */
  29675. this._designatedSlot = -1;
  29676. /** @hidden */
  29677. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29678. /** @hidden */
  29679. this._comparisonFunction = 0;
  29680. /** @hidden */
  29681. this._sphericalPolynomial = null;
  29682. /** @hidden */
  29683. this._lodGenerationScale = 0;
  29684. /** @hidden */
  29685. this._lodGenerationOffset = 0;
  29686. /** @hidden */
  29687. this._isRGBD = false;
  29688. /** @hidden */
  29689. this._references = 1;
  29690. this._engine = engine;
  29691. this._dataSource = dataSource;
  29692. this._webGLTexture = engine._createTexture();
  29693. }
  29694. /**
  29695. * Gets the Engine the texture belongs to.
  29696. * @returns The babylon engine
  29697. */
  29698. InternalTexture.prototype.getEngine = function () {
  29699. return this._engine;
  29700. };
  29701. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29702. /**
  29703. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29704. */
  29705. get: function () {
  29706. return this._dataSource;
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. /**
  29712. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29713. */
  29714. InternalTexture.prototype.incrementReferences = function () {
  29715. this._references++;
  29716. };
  29717. /**
  29718. * Change the size of the texture (not the size of the content)
  29719. * @param width defines the new width
  29720. * @param height defines the new height
  29721. * @param depth defines the new depth (1 by default)
  29722. */
  29723. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29724. if (depth === void 0) { depth = 1; }
  29725. this.width = width;
  29726. this.height = height;
  29727. this.depth = depth;
  29728. this.baseWidth = width;
  29729. this.baseHeight = height;
  29730. this.baseDepth = depth;
  29731. this._size = width * height * depth;
  29732. };
  29733. /** @hidden */
  29734. InternalTexture.prototype._rebuild = function () {
  29735. var _this = this;
  29736. var proxy;
  29737. this.isReady = false;
  29738. this._cachedCoordinatesMode = null;
  29739. this._cachedWrapU = null;
  29740. this._cachedWrapV = null;
  29741. this._cachedAnisotropicFilteringLevel = null;
  29742. switch (this._dataSource) {
  29743. case InternalTexture.DATASOURCE_TEMP:
  29744. return;
  29745. case InternalTexture.DATASOURCE_URL:
  29746. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29747. _this.isReady = true;
  29748. }, null, this._buffer, undefined, this.format);
  29749. proxy._swapAndDie(this);
  29750. return;
  29751. case InternalTexture.DATASOURCE_RAW:
  29752. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29753. proxy._swapAndDie(this);
  29754. this.isReady = true;
  29755. return;
  29756. case InternalTexture.DATASOURCE_RAW3D:
  29757. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29758. proxy._swapAndDie(this);
  29759. this.isReady = true;
  29760. return;
  29761. case InternalTexture.DATASOURCE_DYNAMIC:
  29762. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29763. proxy._swapAndDie(this);
  29764. // The engine will make sure to update content so no need to flag it as isReady = true
  29765. return;
  29766. case InternalTexture.DATASOURCE_RENDERTARGET:
  29767. var options = new BABYLON.RenderTargetCreationOptions();
  29768. options.generateDepthBuffer = this._generateDepthBuffer;
  29769. options.generateMipMaps = this.generateMipMaps;
  29770. options.generateStencilBuffer = this._generateStencilBuffer;
  29771. options.samplingMode = this.samplingMode;
  29772. options.type = this.type;
  29773. if (this.isCube) {
  29774. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29775. }
  29776. else {
  29777. var size = {
  29778. width: this.width,
  29779. height: this.height
  29780. };
  29781. proxy = this._engine.createRenderTargetTexture(size, options);
  29782. }
  29783. proxy._swapAndDie(this);
  29784. this.isReady = true;
  29785. return;
  29786. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29787. var depthTextureOptions = {
  29788. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29789. comparisonFunction: this._comparisonFunction,
  29790. generateStencil: this._generateStencilBuffer,
  29791. isCube: this.isCube
  29792. };
  29793. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29794. proxy._swapAndDie(this);
  29795. this.isReady = true;
  29796. return;
  29797. case InternalTexture.DATASOURCE_CUBE:
  29798. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29799. _this.isReady = true;
  29800. }, null, this.format, this._extension);
  29801. proxy._swapAndDie(this);
  29802. return;
  29803. case InternalTexture.DATASOURCE_CUBERAW:
  29804. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29805. proxy._swapAndDie(this);
  29806. this.isReady = true;
  29807. return;
  29808. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29809. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29810. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29811. _this.isReady = true;
  29812. });
  29813. proxy._swapAndDie(this);
  29814. return;
  29815. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29816. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29817. if (proxy) {
  29818. proxy._swapAndDie(_this);
  29819. }
  29820. _this.isReady = true;
  29821. }, null, this.format, this._extension);
  29822. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29823. return;
  29824. }
  29825. };
  29826. InternalTexture.prototype._swapAndDie = function (target) {
  29827. target._webGLTexture = this._webGLTexture;
  29828. if (this._framebuffer) {
  29829. target._framebuffer = this._framebuffer;
  29830. }
  29831. if (this._depthStencilBuffer) {
  29832. target._depthStencilBuffer = this._depthStencilBuffer;
  29833. }
  29834. if (this._lodTextureHigh) {
  29835. if (target._lodTextureHigh) {
  29836. target._lodTextureHigh.dispose();
  29837. }
  29838. target._lodTextureHigh = this._lodTextureHigh;
  29839. }
  29840. if (this._lodTextureMid) {
  29841. if (target._lodTextureMid) {
  29842. target._lodTextureMid.dispose();
  29843. }
  29844. target._lodTextureMid = this._lodTextureMid;
  29845. }
  29846. if (this._lodTextureLow) {
  29847. if (target._lodTextureLow) {
  29848. target._lodTextureLow.dispose();
  29849. }
  29850. target._lodTextureLow = this._lodTextureLow;
  29851. }
  29852. var cache = this._engine.getLoadedTexturesCache();
  29853. var index = cache.indexOf(this);
  29854. if (index !== -1) {
  29855. cache.splice(index, 1);
  29856. }
  29857. };
  29858. /**
  29859. * Dispose the current allocated resources
  29860. */
  29861. InternalTexture.prototype.dispose = function () {
  29862. if (!this._webGLTexture) {
  29863. return;
  29864. }
  29865. this._references--;
  29866. if (this._references === 0) {
  29867. this._engine._releaseTexture(this);
  29868. this._webGLTexture = null;
  29869. this.previous = null;
  29870. this.next = null;
  29871. }
  29872. };
  29873. /**
  29874. * The source of the texture data is unknown
  29875. */
  29876. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29877. /**
  29878. * Texture data comes from an URL
  29879. */
  29880. InternalTexture.DATASOURCE_URL = 1;
  29881. /**
  29882. * Texture data is only used for temporary storage
  29883. */
  29884. InternalTexture.DATASOURCE_TEMP = 2;
  29885. /**
  29886. * Texture data comes from raw data (ArrayBuffer)
  29887. */
  29888. InternalTexture.DATASOURCE_RAW = 3;
  29889. /**
  29890. * Texture content is dynamic (video or dynamic texture)
  29891. */
  29892. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29893. /**
  29894. * Texture content is generated by rendering to it
  29895. */
  29896. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29897. /**
  29898. * Texture content is part of a multi render target process
  29899. */
  29900. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29901. /**
  29902. * Texture data comes from a cube data file
  29903. */
  29904. InternalTexture.DATASOURCE_CUBE = 7;
  29905. /**
  29906. * Texture data comes from a raw cube data
  29907. */
  29908. InternalTexture.DATASOURCE_CUBERAW = 8;
  29909. /**
  29910. * Texture data come from a prefiltered cube data file
  29911. */
  29912. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29913. /**
  29914. * Texture content is raw 3D data
  29915. */
  29916. InternalTexture.DATASOURCE_RAW3D = 10;
  29917. /**
  29918. * Texture content is a depth texture
  29919. */
  29920. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29921. /**
  29922. * Texture data comes from a raw cube data encoded with RGBD
  29923. */
  29924. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29925. return InternalTexture;
  29926. }());
  29927. BABYLON.InternalTexture = InternalTexture;
  29928. })(BABYLON || (BABYLON = {}));
  29929. //# sourceMappingURL=babylon.internalTexture.js.map
  29930. var BABYLON;
  29931. (function (BABYLON) {
  29932. var BaseTexture = /** @class */ (function () {
  29933. function BaseTexture(scene) {
  29934. this._hasAlpha = false;
  29935. this.getAlphaFromRGB = false;
  29936. this.level = 1;
  29937. this.coordinatesIndex = 0;
  29938. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29939. /**
  29940. * | Value | Type | Description |
  29941. * | ----- | ------------------ | ----------- |
  29942. * | 0 | CLAMP_ADDRESSMODE | |
  29943. * | 1 | WRAP_ADDRESSMODE | |
  29944. * | 2 | MIRROR_ADDRESSMODE | |
  29945. */
  29946. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29947. /**
  29948. * | Value | Type | Description |
  29949. * | ----- | ------------------ | ----------- |
  29950. * | 0 | CLAMP_ADDRESSMODE | |
  29951. * | 1 | WRAP_ADDRESSMODE | |
  29952. * | 2 | MIRROR_ADDRESSMODE | |
  29953. */
  29954. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29955. /**
  29956. * | Value | Type | Description |
  29957. * | ----- | ------------------ | ----------- |
  29958. * | 0 | CLAMP_ADDRESSMODE | |
  29959. * | 1 | WRAP_ADDRESSMODE | |
  29960. * | 2 | MIRROR_ADDRESSMODE | |
  29961. */
  29962. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29963. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29964. this.isCube = false;
  29965. this.is3D = false;
  29966. this.gammaSpace = true;
  29967. this.invertZ = false;
  29968. this.lodLevelInAlpha = false;
  29969. this.isRenderTarget = false;
  29970. this.animations = new Array();
  29971. /**
  29972. * An event triggered when the texture is disposed.
  29973. */
  29974. this.onDisposeObservable = new BABYLON.Observable();
  29975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29976. this._cachedSize = BABYLON.Size.Zero();
  29977. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29978. if (this._scene) {
  29979. this._scene.textures.push(this);
  29980. }
  29981. this._uid = null;
  29982. }
  29983. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29984. get: function () {
  29985. return this._hasAlpha;
  29986. },
  29987. set: function (value) {
  29988. if (this._hasAlpha === value) {
  29989. return;
  29990. }
  29991. this._hasAlpha = value;
  29992. if (this._scene) {
  29993. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29994. }
  29995. },
  29996. enumerable: true,
  29997. configurable: true
  29998. });
  29999. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30000. get: function () {
  30001. return this._coordinatesMode;
  30002. },
  30003. /**
  30004. * How a texture is mapped.
  30005. *
  30006. * | Value | Type | Description |
  30007. * | ----- | ----------------------------------- | ----------- |
  30008. * | 0 | EXPLICIT_MODE | |
  30009. * | 1 | SPHERICAL_MODE | |
  30010. * | 2 | PLANAR_MODE | |
  30011. * | 3 | CUBIC_MODE | |
  30012. * | 4 | PROJECTION_MODE | |
  30013. * | 5 | SKYBOX_MODE | |
  30014. * | 6 | INVCUBIC_MODE | |
  30015. * | 7 | EQUIRECTANGULAR_MODE | |
  30016. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30017. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30018. */
  30019. set: function (value) {
  30020. if (this._coordinatesMode === value) {
  30021. return;
  30022. }
  30023. this._coordinatesMode = value;
  30024. if (this._scene) {
  30025. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30026. }
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30032. /**
  30033. * Gets whether or not the texture contains RGBD data.
  30034. */
  30035. get: function () {
  30036. return this._texture != null && this._texture._isRGBD;
  30037. },
  30038. enumerable: true,
  30039. configurable: true
  30040. });
  30041. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30042. get: function () {
  30043. if (this._texture)
  30044. return this._texture._lodGenerationOffset;
  30045. return 0.0;
  30046. },
  30047. set: function (value) {
  30048. if (this._texture)
  30049. this._texture._lodGenerationOffset = value;
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30055. get: function () {
  30056. if (this._texture)
  30057. return this._texture._lodGenerationScale;
  30058. return 0.0;
  30059. },
  30060. set: function (value) {
  30061. if (this._texture)
  30062. this._texture._lodGenerationScale = value;
  30063. },
  30064. enumerable: true,
  30065. configurable: true
  30066. });
  30067. Object.defineProperty(BaseTexture.prototype, "uid", {
  30068. get: function () {
  30069. if (!this._uid) {
  30070. this._uid = BABYLON.Tools.RandomId();
  30071. }
  30072. return this._uid;
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. BaseTexture.prototype.toString = function () {
  30078. return this.name;
  30079. };
  30080. BaseTexture.prototype.getClassName = function () {
  30081. return "BaseTexture";
  30082. };
  30083. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30084. set: function (callback) {
  30085. if (this._onDisposeObserver) {
  30086. this.onDisposeObservable.remove(this._onDisposeObserver);
  30087. }
  30088. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30094. get: function () {
  30095. return true;
  30096. },
  30097. enumerable: true,
  30098. configurable: true
  30099. });
  30100. BaseTexture.prototype.getScene = function () {
  30101. return this._scene;
  30102. };
  30103. BaseTexture.prototype.getTextureMatrix = function () {
  30104. return BABYLON.Matrix.IdentityReadOnly;
  30105. };
  30106. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30107. return BABYLON.Matrix.IdentityReadOnly;
  30108. };
  30109. BaseTexture.prototype.getInternalTexture = function () {
  30110. return this._texture;
  30111. };
  30112. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30113. return !this.isBlocking || this.isReady();
  30114. };
  30115. BaseTexture.prototype.isReady = function () {
  30116. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30117. this.delayLoad();
  30118. return false;
  30119. }
  30120. if (this._texture) {
  30121. return this._texture.isReady;
  30122. }
  30123. return false;
  30124. };
  30125. BaseTexture.prototype.getSize = function () {
  30126. if (this._texture) {
  30127. if (this._texture.width) {
  30128. this._cachedSize.width = this._texture.width;
  30129. this._cachedSize.height = this._texture.height;
  30130. return this._cachedSize;
  30131. }
  30132. if (this._texture._size) {
  30133. this._cachedSize.width = this._texture._size;
  30134. this._cachedSize.height = this._texture._size;
  30135. return this._cachedSize;
  30136. }
  30137. }
  30138. return this._cachedSize;
  30139. };
  30140. BaseTexture.prototype.getBaseSize = function () {
  30141. if (!this.isReady() || !this._texture)
  30142. return BABYLON.Size.Zero();
  30143. if (this._texture._size) {
  30144. return new BABYLON.Size(this._texture._size, this._texture._size);
  30145. }
  30146. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30147. };
  30148. BaseTexture.prototype.scale = function (ratio) {
  30149. };
  30150. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30151. get: function () {
  30152. return false;
  30153. },
  30154. enumerable: true,
  30155. configurable: true
  30156. });
  30157. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30158. if (!this._scene) {
  30159. return null;
  30160. }
  30161. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30162. for (var index = 0; index < texturesCache.length; index++) {
  30163. var texturesCacheEntry = texturesCache[index];
  30164. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30165. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30166. texturesCacheEntry.incrementReferences();
  30167. return texturesCacheEntry;
  30168. }
  30169. }
  30170. }
  30171. return null;
  30172. };
  30173. BaseTexture.prototype._rebuild = function () {
  30174. };
  30175. BaseTexture.prototype.delayLoad = function () {
  30176. };
  30177. BaseTexture.prototype.clone = function () {
  30178. return null;
  30179. };
  30180. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30181. get: function () {
  30182. if (!this._texture) {
  30183. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30184. }
  30185. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30191. get: function () {
  30192. if (!this._texture) {
  30193. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30194. }
  30195. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30196. },
  30197. enumerable: true,
  30198. configurable: true
  30199. });
  30200. /**
  30201. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30202. * This will returns an RGBA array buffer containing either in values (0-255) or
  30203. * float values (0-1) depending of the underlying buffer type.
  30204. * @param faceIndex The face of the texture to read (in case of cube texture)
  30205. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30206. * @returns The Array buffer containing the pixels data.
  30207. */
  30208. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30209. if (faceIndex === void 0) { faceIndex = 0; }
  30210. if (level === void 0) { level = 0; }
  30211. if (!this._texture) {
  30212. return null;
  30213. }
  30214. var size = this.getSize();
  30215. var width = size.width;
  30216. var height = size.height;
  30217. var scene = this.getScene();
  30218. if (!scene) {
  30219. return null;
  30220. }
  30221. var engine = scene.getEngine();
  30222. if (level != 0) {
  30223. width = width / Math.pow(2, level);
  30224. height = height / Math.pow(2, level);
  30225. width = Math.round(width);
  30226. height = Math.round(height);
  30227. }
  30228. if (this._texture.isCube) {
  30229. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30230. }
  30231. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30232. };
  30233. BaseTexture.prototype.releaseInternalTexture = function () {
  30234. if (this._texture) {
  30235. this._texture.dispose();
  30236. this._texture = null;
  30237. }
  30238. };
  30239. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30240. get: function () {
  30241. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30242. return null;
  30243. }
  30244. if (!this._texture._sphericalPolynomial) {
  30245. this._texture._sphericalPolynomial =
  30246. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30247. }
  30248. return this._texture._sphericalPolynomial;
  30249. },
  30250. set: function (value) {
  30251. if (this._texture) {
  30252. this._texture._sphericalPolynomial = value;
  30253. }
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30259. get: function () {
  30260. if (this._texture) {
  30261. return this._texture._lodTextureHigh;
  30262. }
  30263. return null;
  30264. },
  30265. enumerable: true,
  30266. configurable: true
  30267. });
  30268. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30269. get: function () {
  30270. if (this._texture) {
  30271. return this._texture._lodTextureMid;
  30272. }
  30273. return null;
  30274. },
  30275. enumerable: true,
  30276. configurable: true
  30277. });
  30278. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30279. get: function () {
  30280. if (this._texture) {
  30281. return this._texture._lodTextureLow;
  30282. }
  30283. return null;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. BaseTexture.prototype.dispose = function () {
  30289. if (!this._scene) {
  30290. return;
  30291. }
  30292. // Animations
  30293. this._scene.stopAnimation(this);
  30294. // Remove from scene
  30295. this._scene._removePendingData(this);
  30296. var index = this._scene.textures.indexOf(this);
  30297. if (index >= 0) {
  30298. this._scene.textures.splice(index, 1);
  30299. }
  30300. if (this._texture === undefined) {
  30301. return;
  30302. }
  30303. // Release
  30304. this.releaseInternalTexture();
  30305. // Callback
  30306. this.onDisposeObservable.notifyObservers(this);
  30307. this.onDisposeObservable.clear();
  30308. };
  30309. BaseTexture.prototype.serialize = function () {
  30310. if (!this.name) {
  30311. return null;
  30312. }
  30313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30314. // Animations
  30315. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30316. return serializationObject;
  30317. };
  30318. BaseTexture.WhenAllReady = function (textures, callback) {
  30319. var numRemaining = textures.length;
  30320. if (numRemaining === 0) {
  30321. callback();
  30322. return;
  30323. }
  30324. var _loop_1 = function () {
  30325. texture = textures[i];
  30326. if (texture.isReady()) {
  30327. if (--numRemaining === 0) {
  30328. callback();
  30329. }
  30330. }
  30331. else {
  30332. onLoadObservable = texture.onLoadObservable;
  30333. var onLoadCallback_1 = function () {
  30334. onLoadObservable.removeCallback(onLoadCallback_1);
  30335. if (--numRemaining === 0) {
  30336. callback();
  30337. }
  30338. };
  30339. onLoadObservable.add(onLoadCallback_1);
  30340. }
  30341. };
  30342. var texture, onLoadObservable;
  30343. for (var i = 0; i < textures.length; i++) {
  30344. _loop_1();
  30345. }
  30346. };
  30347. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30348. __decorate([
  30349. BABYLON.serialize()
  30350. ], BaseTexture.prototype, "name", void 0);
  30351. __decorate([
  30352. BABYLON.serialize("hasAlpha")
  30353. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30354. __decorate([
  30355. BABYLON.serialize()
  30356. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30357. __decorate([
  30358. BABYLON.serialize()
  30359. ], BaseTexture.prototype, "level", void 0);
  30360. __decorate([
  30361. BABYLON.serialize()
  30362. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30363. __decorate([
  30364. BABYLON.serialize("coordinatesMode")
  30365. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30366. __decorate([
  30367. BABYLON.serialize()
  30368. ], BaseTexture.prototype, "wrapU", void 0);
  30369. __decorate([
  30370. BABYLON.serialize()
  30371. ], BaseTexture.prototype, "wrapV", void 0);
  30372. __decorate([
  30373. BABYLON.serialize()
  30374. ], BaseTexture.prototype, "wrapR", void 0);
  30375. __decorate([
  30376. BABYLON.serialize()
  30377. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30378. __decorate([
  30379. BABYLON.serialize()
  30380. ], BaseTexture.prototype, "isCube", void 0);
  30381. __decorate([
  30382. BABYLON.serialize()
  30383. ], BaseTexture.prototype, "is3D", void 0);
  30384. __decorate([
  30385. BABYLON.serialize()
  30386. ], BaseTexture.prototype, "gammaSpace", void 0);
  30387. __decorate([
  30388. BABYLON.serialize()
  30389. ], BaseTexture.prototype, "invertZ", void 0);
  30390. __decorate([
  30391. BABYLON.serialize()
  30392. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30393. __decorate([
  30394. BABYLON.serialize()
  30395. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30396. __decorate([
  30397. BABYLON.serialize()
  30398. ], BaseTexture.prototype, "lodGenerationScale", null);
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30402. return BaseTexture;
  30403. }());
  30404. BABYLON.BaseTexture = BaseTexture;
  30405. })(BABYLON || (BABYLON = {}));
  30406. //# sourceMappingURL=babylon.baseTexture.js.map
  30407. var BABYLON;
  30408. (function (BABYLON) {
  30409. var Texture = /** @class */ (function (_super) {
  30410. __extends(Texture, _super);
  30411. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30412. if (noMipmap === void 0) { noMipmap = false; }
  30413. if (invertY === void 0) { invertY = true; }
  30414. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30415. if (onLoad === void 0) { onLoad = null; }
  30416. if (onError === void 0) { onError = null; }
  30417. if (buffer === void 0) { buffer = null; }
  30418. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30419. var _this = _super.call(this, scene) || this;
  30420. _this.uOffset = 0;
  30421. _this.vOffset = 0;
  30422. _this.uScale = 1.0;
  30423. _this.vScale = 1.0;
  30424. _this.uAng = 0;
  30425. _this.vAng = 0;
  30426. _this.wAng = 0;
  30427. /**
  30428. * Defines the center of rotation (U)
  30429. */
  30430. _this.uRotationCenter = 0.5;
  30431. /**
  30432. * Defines the center of rotation (V)
  30433. */
  30434. _this.vRotationCenter = 0.5;
  30435. /**
  30436. * Defines the center of rotation (W)
  30437. */
  30438. _this.wRotationCenter = 0.5;
  30439. _this._isBlocking = true;
  30440. _this.name = url || "";
  30441. _this.url = url;
  30442. _this._noMipmap = noMipmap;
  30443. _this._invertY = invertY;
  30444. _this._samplingMode = samplingMode;
  30445. _this._buffer = buffer;
  30446. _this._deleteBuffer = deleteBuffer;
  30447. if (format) {
  30448. _this._format = format;
  30449. }
  30450. scene = _this.getScene();
  30451. if (!scene) {
  30452. return _this;
  30453. }
  30454. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30455. var load = function () {
  30456. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30457. _this.onLoadObservable.notifyObservers(_this);
  30458. }
  30459. if (onLoad) {
  30460. onLoad();
  30461. }
  30462. if (!_this.isBlocking && scene) {
  30463. scene.resetCachedMaterial();
  30464. }
  30465. };
  30466. if (!_this.url) {
  30467. _this._delayedOnLoad = load;
  30468. _this._delayedOnError = onError;
  30469. return _this;
  30470. }
  30471. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30472. if (!_this._texture) {
  30473. if (!scene.useDelayedTextureLoading) {
  30474. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30475. if (deleteBuffer) {
  30476. delete _this._buffer;
  30477. }
  30478. }
  30479. else {
  30480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30481. _this._delayedOnLoad = load;
  30482. _this._delayedOnError = onError;
  30483. }
  30484. }
  30485. else {
  30486. if (_this._texture.isReady) {
  30487. BABYLON.Tools.SetImmediate(function () { return load(); });
  30488. }
  30489. else {
  30490. _this._texture.onLoadedObservable.add(load);
  30491. }
  30492. }
  30493. return _this;
  30494. }
  30495. Object.defineProperty(Texture.prototype, "noMipmap", {
  30496. get: function () {
  30497. return this._noMipmap;
  30498. },
  30499. enumerable: true,
  30500. configurable: true
  30501. });
  30502. Object.defineProperty(Texture.prototype, "isBlocking", {
  30503. get: function () {
  30504. return this._isBlocking;
  30505. },
  30506. set: function (value) {
  30507. this._isBlocking = value;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(Texture.prototype, "samplingMode", {
  30513. get: function () {
  30514. return this._samplingMode;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. /**
  30520. * Update the url (and optional buffer) of this texture if url was null during construction.
  30521. * @param url the url of the texture
  30522. * @param buffer the buffer of the texture (defaults to null)
  30523. */
  30524. Texture.prototype.updateURL = function (url, buffer) {
  30525. if (buffer === void 0) { buffer = null; }
  30526. if (this.url) {
  30527. throw new Error("URL is already set");
  30528. }
  30529. this.url = url;
  30530. this._buffer = buffer;
  30531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30532. this.delayLoad();
  30533. };
  30534. Texture.prototype.delayLoad = function () {
  30535. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30536. return;
  30537. }
  30538. var scene = this.getScene();
  30539. if (!scene) {
  30540. return;
  30541. }
  30542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30543. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30544. if (!this._texture) {
  30545. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30546. if (this._deleteBuffer) {
  30547. delete this._buffer;
  30548. }
  30549. }
  30550. else {
  30551. if (this._delayedOnLoad) {
  30552. if (this._texture.isReady) {
  30553. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30554. }
  30555. else {
  30556. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30557. }
  30558. }
  30559. }
  30560. this._delayedOnLoad = null;
  30561. this._delayedOnError = null;
  30562. };
  30563. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30564. if (!this._texture) {
  30565. return;
  30566. }
  30567. var scene = this.getScene();
  30568. if (!scene) {
  30569. return;
  30570. }
  30571. this._samplingMode = samplingMode;
  30572. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30573. };
  30574. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30575. x *= this.uScale;
  30576. y *= this.vScale;
  30577. x -= this.uRotationCenter * this.uScale;
  30578. y -= this.vRotationCenter * this.vScale;
  30579. z -= this.wRotationCenter;
  30580. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30581. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30582. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30583. t.z += this.wRotationCenter;
  30584. };
  30585. Texture.prototype.getTextureMatrix = function () {
  30586. var _this = this;
  30587. if (this.uOffset === this._cachedUOffset &&
  30588. this.vOffset === this._cachedVOffset &&
  30589. this.uScale === this._cachedUScale &&
  30590. this.vScale === this._cachedVScale &&
  30591. this.uAng === this._cachedUAng &&
  30592. this.vAng === this._cachedVAng &&
  30593. this.wAng === this._cachedWAng) {
  30594. return this._cachedTextureMatrix;
  30595. }
  30596. this._cachedUOffset = this.uOffset;
  30597. this._cachedVOffset = this.vOffset;
  30598. this._cachedUScale = this.uScale;
  30599. this._cachedVScale = this.vScale;
  30600. this._cachedUAng = this.uAng;
  30601. this._cachedVAng = this.vAng;
  30602. this._cachedWAng = this.wAng;
  30603. if (!this._cachedTextureMatrix) {
  30604. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30605. this._rowGenerationMatrix = new BABYLON.Matrix();
  30606. this._t0 = BABYLON.Vector3.Zero();
  30607. this._t1 = BABYLON.Vector3.Zero();
  30608. this._t2 = BABYLON.Vector3.Zero();
  30609. }
  30610. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30611. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30612. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30613. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30614. this._t1.subtractInPlace(this._t0);
  30615. this._t2.subtractInPlace(this._t0);
  30616. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30617. this._cachedTextureMatrix.m[0] = this._t1.x;
  30618. this._cachedTextureMatrix.m[1] = this._t1.y;
  30619. this._cachedTextureMatrix.m[2] = this._t1.z;
  30620. this._cachedTextureMatrix.m[4] = this._t2.x;
  30621. this._cachedTextureMatrix.m[5] = this._t2.y;
  30622. this._cachedTextureMatrix.m[6] = this._t2.z;
  30623. this._cachedTextureMatrix.m[8] = this._t0.x;
  30624. this._cachedTextureMatrix.m[9] = this._t0.y;
  30625. this._cachedTextureMatrix.m[10] = this._t0.z;
  30626. var scene = this.getScene();
  30627. if (!scene) {
  30628. return this._cachedTextureMatrix;
  30629. }
  30630. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30631. return mat.hasTexture(_this);
  30632. });
  30633. return this._cachedTextureMatrix;
  30634. };
  30635. Texture.prototype.getReflectionTextureMatrix = function () {
  30636. var _this = this;
  30637. var scene = this.getScene();
  30638. if (!scene) {
  30639. return this._cachedTextureMatrix;
  30640. }
  30641. if (this.uOffset === this._cachedUOffset &&
  30642. this.vOffset === this._cachedVOffset &&
  30643. this.uScale === this._cachedUScale &&
  30644. this.vScale === this._cachedVScale &&
  30645. this.coordinatesMode === this._cachedCoordinatesMode) {
  30646. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30647. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30648. return this._cachedTextureMatrix;
  30649. }
  30650. }
  30651. else {
  30652. return this._cachedTextureMatrix;
  30653. }
  30654. }
  30655. if (!this._cachedTextureMatrix) {
  30656. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30657. }
  30658. if (!this._projectionModeMatrix) {
  30659. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30660. }
  30661. this._cachedUOffset = this.uOffset;
  30662. this._cachedVOffset = this.vOffset;
  30663. this._cachedUScale = this.uScale;
  30664. this._cachedVScale = this.vScale;
  30665. this._cachedCoordinatesMode = this.coordinatesMode;
  30666. switch (this.coordinatesMode) {
  30667. case Texture.PLANAR_MODE:
  30668. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30669. this._cachedTextureMatrix[0] = this.uScale;
  30670. this._cachedTextureMatrix[5] = this.vScale;
  30671. this._cachedTextureMatrix[12] = this.uOffset;
  30672. this._cachedTextureMatrix[13] = this.vOffset;
  30673. break;
  30674. case Texture.PROJECTION_MODE:
  30675. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30676. this._projectionModeMatrix.m[0] = 0.5;
  30677. this._projectionModeMatrix.m[5] = -0.5;
  30678. this._projectionModeMatrix.m[10] = 0.0;
  30679. this._projectionModeMatrix.m[12] = 0.5;
  30680. this._projectionModeMatrix.m[13] = 0.5;
  30681. this._projectionModeMatrix.m[14] = 1.0;
  30682. this._projectionModeMatrix.m[15] = 1.0;
  30683. var projectionMatrix = scene.getProjectionMatrix();
  30684. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30685. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30686. break;
  30687. default:
  30688. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30689. break;
  30690. }
  30691. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30692. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30693. });
  30694. return this._cachedTextureMatrix;
  30695. };
  30696. Texture.prototype.clone = function () {
  30697. var _this = this;
  30698. return BABYLON.SerializationHelper.Clone(function () {
  30699. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30700. }, this);
  30701. };
  30702. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30703. get: function () {
  30704. if (!this._onLoadObservable) {
  30705. this._onLoadObservable = new BABYLON.Observable();
  30706. }
  30707. return this._onLoadObservable;
  30708. },
  30709. enumerable: true,
  30710. configurable: true
  30711. });
  30712. Texture.prototype.serialize = function () {
  30713. var serializationObject = _super.prototype.serialize.call(this);
  30714. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30715. serializationObject.base64String = this._buffer;
  30716. serializationObject.name = serializationObject.name.replace("data:", "");
  30717. }
  30718. serializationObject.invertY = this._invertY;
  30719. serializationObject.samplingMode = this.samplingMode;
  30720. return serializationObject;
  30721. };
  30722. Texture.prototype.getClassName = function () {
  30723. return "Texture";
  30724. };
  30725. Texture.prototype.dispose = function () {
  30726. _super.prototype.dispose.call(this);
  30727. if (this._onLoadObservable) {
  30728. this._onLoadObservable.clear();
  30729. this._onLoadObservable = null;
  30730. }
  30731. this._delayedOnLoad = null;
  30732. this._delayedOnError = null;
  30733. };
  30734. // Statics
  30735. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30736. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30737. if (onLoad === void 0) { onLoad = null; }
  30738. if (onError === void 0) { onError = null; }
  30739. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30740. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30741. };
  30742. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30743. if (parsedTexture.customType) {
  30744. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30745. // Update Sampling Mode
  30746. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30747. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30748. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30749. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30750. }
  30751. }
  30752. return parsedCustomTexture;
  30753. }
  30754. if (parsedTexture.isCube) {
  30755. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30756. }
  30757. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30758. return null;
  30759. }
  30760. var texture = BABYLON.SerializationHelper.Parse(function () {
  30761. var generateMipMaps = true;
  30762. if (parsedTexture.noMipmap) {
  30763. generateMipMaps = false;
  30764. }
  30765. if (parsedTexture.mirrorPlane) {
  30766. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30767. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30768. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30769. return mirrorTexture;
  30770. }
  30771. else if (parsedTexture.isRenderTarget) {
  30772. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30773. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30774. return renderTargetTexture;
  30775. }
  30776. else {
  30777. var texture;
  30778. if (parsedTexture.base64String) {
  30779. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30780. }
  30781. else {
  30782. var url = rootUrl + parsedTexture.name;
  30783. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30784. url = parsedTexture.url;
  30785. }
  30786. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30787. }
  30788. return texture;
  30789. }
  30790. }, parsedTexture, scene);
  30791. // Update Sampling Mode
  30792. if (parsedTexture.samplingMode) {
  30793. var sampling = parsedTexture.samplingMode;
  30794. if (texture._samplingMode !== sampling) {
  30795. texture.updateSamplingMode(sampling);
  30796. }
  30797. }
  30798. // Animations
  30799. if (parsedTexture.animations) {
  30800. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30801. var parsedAnimation = parsedTexture.animations[animationIndex];
  30802. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30803. }
  30804. }
  30805. return texture;
  30806. };
  30807. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30808. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30809. if (noMipmap === void 0) { noMipmap = false; }
  30810. if (invertY === void 0) { invertY = true; }
  30811. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30812. if (onLoad === void 0) { onLoad = null; }
  30813. if (onError === void 0) { onError = null; }
  30814. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30815. if (name.substr(0, 5) !== "data:") {
  30816. name = "data:" + name;
  30817. }
  30818. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30819. };
  30820. // Constants
  30821. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30822. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30823. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30824. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30825. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30826. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30827. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30828. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30829. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30830. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30831. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30832. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30833. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30834. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30835. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30836. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30837. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30838. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30839. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30840. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30841. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30842. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30843. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30844. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30845. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30846. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30847. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30848. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30849. /**
  30850. * 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
  30851. */
  30852. Texture.UseSerializedUrlIfAny = false;
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], Texture.prototype, "url", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], Texture.prototype, "uOffset", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], Texture.prototype, "vOffset", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], Texture.prototype, "uScale", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], Texture.prototype, "vScale", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], Texture.prototype, "uAng", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], Texture.prototype, "vAng", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], Texture.prototype, "wAng", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], Texture.prototype, "uRotationCenter", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], Texture.prototype, "vRotationCenter", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], Texture.prototype, "wRotationCenter", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], Texture.prototype, "isBlocking", null);
  30889. return Texture;
  30890. }(BABYLON.BaseTexture));
  30891. BABYLON.Texture = Texture;
  30892. })(BABYLON || (BABYLON = {}));
  30893. //# sourceMappingURL=babylon.texture.js.map
  30894. var BABYLON;
  30895. (function (BABYLON) {
  30896. /**
  30897. * @hidden
  30898. **/
  30899. var _InstancesBatch = /** @class */ (function () {
  30900. function _InstancesBatch() {
  30901. this.mustReturn = false;
  30902. this.visibleInstances = new Array();
  30903. this.renderSelf = new Array();
  30904. }
  30905. return _InstancesBatch;
  30906. }());
  30907. BABYLON._InstancesBatch = _InstancesBatch;
  30908. var Mesh = /** @class */ (function (_super) {
  30909. __extends(Mesh, _super);
  30910. /**
  30911. * @constructor
  30912. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30913. * @param {Scene} scene The scene to add this mesh to.
  30914. * @param {Node} parent The parent of this mesh, if it has one
  30915. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30916. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30917. * When false, achieved by calling a clone(), also passing False.
  30918. * This will make creation of children, recursive.
  30919. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30920. */
  30921. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30922. if (scene === void 0) { scene = null; }
  30923. if (parent === void 0) { parent = null; }
  30924. if (source === void 0) { source = null; }
  30925. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30926. var _this = _super.call(this, name, scene) || this;
  30927. // Events
  30928. /**
  30929. * An event triggered before rendering the mesh
  30930. */
  30931. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30932. /**
  30933. * An event triggered after rendering the mesh
  30934. */
  30935. _this.onAfterRenderObservable = new BABYLON.Observable();
  30936. /**
  30937. * An event triggered before drawing the mesh
  30938. */
  30939. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30940. // Members
  30941. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30942. _this.instances = new Array();
  30943. _this._LODLevels = new Array();
  30944. _this._visibleInstances = {};
  30945. _this._renderIdForInstances = new Array();
  30946. _this._batchCache = new _InstancesBatch();
  30947. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30948. // Use by builder only to know what orientation were the mesh build in.
  30949. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30950. _this.overrideMaterialSideOrientation = null;
  30951. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30952. // Will be used to save a source mesh reference, If any
  30953. _this._source = null;
  30954. scene = _this.getScene();
  30955. if (source) {
  30956. // Geometry
  30957. if (source._geometry) {
  30958. source._geometry.applyToMesh(_this);
  30959. }
  30960. // Deep copy
  30961. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30962. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30963. // Source mesh
  30964. _this._source = source;
  30965. // Metadata
  30966. if (source.metadata && source.metadata.clone) {
  30967. _this.metadata = source.metadata.clone();
  30968. }
  30969. else {
  30970. _this.metadata = source.metadata;
  30971. }
  30972. // Tags
  30973. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30974. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30975. }
  30976. // Parent
  30977. _this.parent = source.parent;
  30978. // Pivot
  30979. _this.setPivotMatrix(source.getPivotMatrix());
  30980. _this.id = name + "." + source.id;
  30981. // Material
  30982. _this.material = source.material;
  30983. var index;
  30984. if (!doNotCloneChildren) {
  30985. // Children
  30986. var directDescendants = source.getDescendants(true);
  30987. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30988. var child = directDescendants[index_1];
  30989. if (child.clone) {
  30990. child.clone(name + "." + child.name, _this);
  30991. }
  30992. }
  30993. }
  30994. // Physics clone
  30995. var physicsEngine = _this.getScene().getPhysicsEngine();
  30996. if (clonePhysicsImpostor && physicsEngine) {
  30997. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30998. if (impostor) {
  30999. _this.physicsImpostor = impostor.clone(_this);
  31000. }
  31001. }
  31002. // Particles
  31003. for (index = 0; index < scene.particleSystems.length; index++) {
  31004. var system = scene.particleSystems[index];
  31005. if (system.emitter === source) {
  31006. system.clone(system.name, _this);
  31007. }
  31008. }
  31009. _this.refreshBoundingInfo();
  31010. _this.computeWorldMatrix(true);
  31011. }
  31012. // Parent
  31013. if (parent !== null) {
  31014. _this.parent = parent;
  31015. }
  31016. return _this;
  31017. }
  31018. Object.defineProperty(Mesh, "FRONTSIDE", {
  31019. /**
  31020. * Mesh side orientation : usually the external or front surface
  31021. */
  31022. get: function () {
  31023. return Mesh._FRONTSIDE;
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Mesh, "BACKSIDE", {
  31029. /**
  31030. * Mesh side orientation : usually the internal or back surface
  31031. */
  31032. get: function () {
  31033. return Mesh._BACKSIDE;
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31039. /**
  31040. * Mesh side orientation : both internal and external or front and back surfaces
  31041. */
  31042. get: function () {
  31043. return Mesh._DOUBLESIDE;
  31044. },
  31045. enumerable: true,
  31046. configurable: true
  31047. });
  31048. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31049. /**
  31050. * Mesh side orientation : by default, `FRONTSIDE`
  31051. */
  31052. get: function () {
  31053. return Mesh._DEFAULTSIDE;
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. Object.defineProperty(Mesh, "NO_CAP", {
  31059. /**
  31060. * Mesh cap setting : no cap
  31061. */
  31062. get: function () {
  31063. return Mesh._NO_CAP;
  31064. },
  31065. enumerable: true,
  31066. configurable: true
  31067. });
  31068. Object.defineProperty(Mesh, "CAP_START", {
  31069. /**
  31070. * Mesh cap setting : one cap at the beginning of the mesh
  31071. */
  31072. get: function () {
  31073. return Mesh._CAP_START;
  31074. },
  31075. enumerable: true,
  31076. configurable: true
  31077. });
  31078. Object.defineProperty(Mesh, "CAP_END", {
  31079. /**
  31080. * Mesh cap setting : one cap at the end of the mesh
  31081. */
  31082. get: function () {
  31083. return Mesh._CAP_END;
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. Object.defineProperty(Mesh, "CAP_ALL", {
  31089. /**
  31090. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31091. */
  31092. get: function () {
  31093. return Mesh._CAP_ALL;
  31094. },
  31095. enumerable: true,
  31096. configurable: true
  31097. });
  31098. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31099. set: function (callback) {
  31100. if (this._onBeforeDrawObserver) {
  31101. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31102. }
  31103. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31104. },
  31105. enumerable: true,
  31106. configurable: true
  31107. });
  31108. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31109. get: function () {
  31110. return this._morphTargetManager;
  31111. },
  31112. set: function (value) {
  31113. if (this._morphTargetManager === value) {
  31114. return;
  31115. }
  31116. this._morphTargetManager = value;
  31117. this._syncGeometryWithMorphTargetManager();
  31118. },
  31119. enumerable: true,
  31120. configurable: true
  31121. });
  31122. Object.defineProperty(Mesh.prototype, "source", {
  31123. get: function () {
  31124. return this._source;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31130. get: function () {
  31131. return this._unIndexed;
  31132. },
  31133. set: function (value) {
  31134. if (this._unIndexed !== value) {
  31135. this._unIndexed = value;
  31136. this._markSubMeshesAsAttributesDirty();
  31137. }
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. // Methods
  31143. /**
  31144. * Returns the string "Mesh".
  31145. */
  31146. Mesh.prototype.getClassName = function () {
  31147. return "Mesh";
  31148. };
  31149. /**
  31150. * Returns a string.
  31151. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31152. */
  31153. Mesh.prototype.toString = function (fullDetails) {
  31154. var ret = _super.prototype.toString.call(this, fullDetails);
  31155. ret += ", n vertices: " + this.getTotalVertices();
  31156. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31157. if (this.animations) {
  31158. for (var i = 0; i < this.animations.length; i++) {
  31159. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31160. }
  31161. }
  31162. if (fullDetails) {
  31163. if (this._geometry) {
  31164. var ib = this.getIndices();
  31165. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31166. if (vb && ib) {
  31167. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31168. }
  31169. }
  31170. else {
  31171. ret += ", flat shading: UNKNOWN";
  31172. }
  31173. }
  31174. return ret;
  31175. };
  31176. Mesh.prototype._unBindEffect = function () {
  31177. _super.prototype._unBindEffect.call(this);
  31178. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31179. var instance = _a[_i];
  31180. instance._unBindEffect();
  31181. }
  31182. };
  31183. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31184. /**
  31185. * True if the mesh has some Levels Of Details (LOD).
  31186. * Returns a boolean.
  31187. */
  31188. get: function () {
  31189. return this._LODLevels.length > 0;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. /**
  31195. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31196. * @returns an array of {BABYLON.MeshLODLevel}
  31197. */
  31198. Mesh.prototype.getLODLevels = function () {
  31199. return this._LODLevels;
  31200. };
  31201. Mesh.prototype._sortLODLevels = function () {
  31202. this._LODLevels.sort(function (a, b) {
  31203. if (a.distance < b.distance) {
  31204. return 1;
  31205. }
  31206. if (a.distance > b.distance) {
  31207. return -1;
  31208. }
  31209. return 0;
  31210. });
  31211. };
  31212. /**
  31213. * Add a mesh as LOD level triggered at the given distance.
  31214. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31215. * @param distance The distance from the center of the object to show this level
  31216. * @param mesh The mesh to be added as LOD level (can be null)
  31217. * @return This mesh (for chaining)
  31218. */
  31219. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31220. if (mesh && mesh._masterMesh) {
  31221. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31222. return this;
  31223. }
  31224. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31225. this._LODLevels.push(level);
  31226. if (mesh) {
  31227. mesh._masterMesh = this;
  31228. }
  31229. this._sortLODLevels();
  31230. return this;
  31231. };
  31232. /**
  31233. * Returns the LOD level mesh at the passed distance or null if not found.
  31234. * It is related to the method `addLODLevel(distance, mesh)`.
  31235. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31236. * Returns an object Mesh or `null`.
  31237. */
  31238. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31239. for (var index = 0; index < this._LODLevels.length; index++) {
  31240. var level = this._LODLevels[index];
  31241. if (level.distance === distance) {
  31242. return level.mesh;
  31243. }
  31244. }
  31245. return null;
  31246. };
  31247. /**
  31248. * Remove a mesh from the LOD array
  31249. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31250. * @param {Mesh} mesh The mesh to be removed.
  31251. * @return {Mesh} This mesh (for chaining)
  31252. */
  31253. Mesh.prototype.removeLODLevel = function (mesh) {
  31254. for (var index = 0; index < this._LODLevels.length; index++) {
  31255. if (this._LODLevels[index].mesh === mesh) {
  31256. this._LODLevels.splice(index, 1);
  31257. if (mesh) {
  31258. mesh._masterMesh = null;
  31259. }
  31260. }
  31261. }
  31262. this._sortLODLevels();
  31263. return this;
  31264. };
  31265. /**
  31266. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31267. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31268. */
  31269. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31270. if (!this._LODLevels || this._LODLevels.length === 0) {
  31271. return this;
  31272. }
  31273. var bSphere;
  31274. if (boundingSphere) {
  31275. bSphere = boundingSphere;
  31276. }
  31277. else {
  31278. var boundingInfo = this.getBoundingInfo();
  31279. bSphere = boundingInfo.boundingSphere;
  31280. }
  31281. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31282. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31283. if (this.onLODLevelSelection) {
  31284. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31285. }
  31286. return this;
  31287. }
  31288. for (var index = 0; index < this._LODLevels.length; index++) {
  31289. var level = this._LODLevels[index];
  31290. if (level.distance < distanceToCamera) {
  31291. if (level.mesh) {
  31292. level.mesh._preActivate();
  31293. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31294. }
  31295. if (this.onLODLevelSelection) {
  31296. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31297. }
  31298. return level.mesh;
  31299. }
  31300. }
  31301. if (this.onLODLevelSelection) {
  31302. this.onLODLevelSelection(distanceToCamera, this, this);
  31303. }
  31304. return this;
  31305. };
  31306. Object.defineProperty(Mesh.prototype, "geometry", {
  31307. /**
  31308. * Returns the mesh internal Geometry object.
  31309. */
  31310. get: function () {
  31311. return this._geometry;
  31312. },
  31313. enumerable: true,
  31314. configurable: true
  31315. });
  31316. /**
  31317. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31318. */
  31319. Mesh.prototype.getTotalVertices = function () {
  31320. if (this._geometry === null || this._geometry === undefined) {
  31321. return 0;
  31322. }
  31323. return this._geometry.getTotalVertices();
  31324. };
  31325. /**
  31326. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31327. * 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.
  31328. * You can force the copy with forceCopy === true
  31329. * Returns null if the mesh has no geometry or no vertex buffer.
  31330. * Possible `kind` values :
  31331. * - BABYLON.VertexBuffer.PositionKind
  31332. * - BABYLON.VertexBuffer.UVKind
  31333. * - BABYLON.VertexBuffer.UV2Kind
  31334. * - BABYLON.VertexBuffer.UV3Kind
  31335. * - BABYLON.VertexBuffer.UV4Kind
  31336. * - BABYLON.VertexBuffer.UV5Kind
  31337. * - BABYLON.VertexBuffer.UV6Kind
  31338. * - BABYLON.VertexBuffer.ColorKind
  31339. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31340. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31341. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31342. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31343. */
  31344. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31345. if (!this._geometry) {
  31346. return null;
  31347. }
  31348. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31349. };
  31350. /**
  31351. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31352. * Returns `null` if the mesh has no geometry.
  31353. * Possible `kind` values :
  31354. * - BABYLON.VertexBuffer.PositionKind
  31355. * - BABYLON.VertexBuffer.UVKind
  31356. * - BABYLON.VertexBuffer.UV2Kind
  31357. * - BABYLON.VertexBuffer.UV3Kind
  31358. * - BABYLON.VertexBuffer.UV4Kind
  31359. * - BABYLON.VertexBuffer.UV5Kind
  31360. * - BABYLON.VertexBuffer.UV6Kind
  31361. * - BABYLON.VertexBuffer.ColorKind
  31362. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31363. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31364. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31365. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31366. */
  31367. Mesh.prototype.getVertexBuffer = function (kind) {
  31368. if (!this._geometry) {
  31369. return null;
  31370. }
  31371. return this._geometry.getVertexBuffer(kind);
  31372. };
  31373. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31374. if (!this._geometry) {
  31375. if (this._delayInfo) {
  31376. return this._delayInfo.indexOf(kind) !== -1;
  31377. }
  31378. return false;
  31379. }
  31380. return this._geometry.isVerticesDataPresent(kind);
  31381. };
  31382. /**
  31383. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31384. * Possible `kind` values :
  31385. * - BABYLON.VertexBuffer.PositionKind
  31386. * - BABYLON.VertexBuffer.UVKind
  31387. * - BABYLON.VertexBuffer.UV2Kind
  31388. * - BABYLON.VertexBuffer.UV3Kind
  31389. * - BABYLON.VertexBuffer.UV4Kind
  31390. * - BABYLON.VertexBuffer.UV5Kind
  31391. * - BABYLON.VertexBuffer.UV6Kind
  31392. * - BABYLON.VertexBuffer.ColorKind
  31393. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31394. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31395. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31396. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31397. */
  31398. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31399. if (!this._geometry) {
  31400. if (this._delayInfo) {
  31401. return this._delayInfo.indexOf(kind) !== -1;
  31402. }
  31403. return false;
  31404. }
  31405. return this._geometry.isVertexBufferUpdatable(kind);
  31406. };
  31407. /**
  31408. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31409. * Possible `kind` values :
  31410. * - BABYLON.VertexBuffer.PositionKind
  31411. * - BABYLON.VertexBuffer.UVKind
  31412. * - BABYLON.VertexBuffer.UV2Kind
  31413. * - BABYLON.VertexBuffer.UV3Kind
  31414. * - BABYLON.VertexBuffer.UV4Kind
  31415. * - BABYLON.VertexBuffer.UV5Kind
  31416. * - BABYLON.VertexBuffer.UV6Kind
  31417. * - BABYLON.VertexBuffer.ColorKind
  31418. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31419. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31420. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31421. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31422. */
  31423. Mesh.prototype.getVerticesDataKinds = function () {
  31424. if (!this._geometry) {
  31425. var result = new Array();
  31426. if (this._delayInfo) {
  31427. this._delayInfo.forEach(function (kind, index, array) {
  31428. result.push(kind);
  31429. });
  31430. }
  31431. return result;
  31432. }
  31433. return this._geometry.getVerticesDataKinds();
  31434. };
  31435. /**
  31436. * Returns a positive integer : the total number of indices in this mesh geometry.
  31437. * Returns zero if the mesh has no geometry.
  31438. */
  31439. Mesh.prototype.getTotalIndices = function () {
  31440. if (!this._geometry) {
  31441. return 0;
  31442. }
  31443. return this._geometry.getTotalIndices();
  31444. };
  31445. /**
  31446. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31447. * 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.
  31448. * Returns an empty array if the mesh has no geometry.
  31449. */
  31450. Mesh.prototype.getIndices = function (copyWhenShared) {
  31451. if (!this._geometry) {
  31452. return [];
  31453. }
  31454. return this._geometry.getIndices(copyWhenShared);
  31455. };
  31456. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31457. get: function () {
  31458. return this._masterMesh !== null && this._masterMesh !== undefined;
  31459. },
  31460. enumerable: true,
  31461. configurable: true
  31462. });
  31463. /**
  31464. * Determine if the current mesh is ready to be rendered
  31465. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31466. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31467. * @returns true if all associated assets are ready (material, textures, shaders)
  31468. */
  31469. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31470. if (completeCheck === void 0) { completeCheck = false; }
  31471. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31472. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31473. return false;
  31474. }
  31475. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31476. return false;
  31477. }
  31478. if (!this.subMeshes || this.subMeshes.length === 0) {
  31479. return true;
  31480. }
  31481. if (!completeCheck) {
  31482. return true;
  31483. }
  31484. var engine = this.getEngine();
  31485. var scene = this.getScene();
  31486. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31487. this.computeWorldMatrix();
  31488. var mat = this.material || scene.defaultMaterial;
  31489. if (mat) {
  31490. if (mat.storeEffectOnSubMeshes) {
  31491. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31492. var subMesh = _a[_i];
  31493. var effectiveMaterial = subMesh.getMaterial();
  31494. if (effectiveMaterial) {
  31495. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31496. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31497. return false;
  31498. }
  31499. }
  31500. else {
  31501. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31502. return false;
  31503. }
  31504. }
  31505. }
  31506. }
  31507. }
  31508. else {
  31509. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31510. return false;
  31511. }
  31512. }
  31513. }
  31514. // Shadows
  31515. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31516. var light = _c[_b];
  31517. var generator = light.getShadowGenerator();
  31518. if (generator) {
  31519. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31520. var subMesh = _e[_d];
  31521. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31522. return false;
  31523. }
  31524. }
  31525. }
  31526. }
  31527. // LOD
  31528. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31529. var lod = _g[_f];
  31530. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31531. return false;
  31532. }
  31533. }
  31534. return true;
  31535. };
  31536. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31537. /**
  31538. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31539. * This property is pertinent only for updatable parametric shapes.
  31540. */
  31541. get: function () {
  31542. return this._areNormalsFrozen;
  31543. },
  31544. enumerable: true,
  31545. configurable: true
  31546. });
  31547. /**
  31548. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31549. * It has no effect at all on other shapes.
  31550. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31551. * Returns the Mesh.
  31552. */
  31553. Mesh.prototype.freezeNormals = function () {
  31554. this._areNormalsFrozen = true;
  31555. return this;
  31556. };
  31557. /**
  31558. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31559. * It has no effect at all on other shapes.
  31560. * It reactivates the mesh normals computation if it was previously frozen.
  31561. * Returns the Mesh.
  31562. */
  31563. Mesh.prototype.unfreezeNormals = function () {
  31564. this._areNormalsFrozen = false;
  31565. return this;
  31566. };
  31567. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31568. /**
  31569. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31570. */
  31571. set: function (count) {
  31572. this._overridenInstanceCount = count;
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. // Methods
  31578. Mesh.prototype._preActivate = function () {
  31579. var sceneRenderId = this.getScene().getRenderId();
  31580. if (this._preActivateId === sceneRenderId) {
  31581. return this;
  31582. }
  31583. this._preActivateId = sceneRenderId;
  31584. this._visibleInstances = null;
  31585. return this;
  31586. };
  31587. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31588. if (this._visibleInstances) {
  31589. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31590. }
  31591. return this;
  31592. };
  31593. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31594. if (!this._visibleInstances) {
  31595. this._visibleInstances = {};
  31596. this._visibleInstances.defaultRenderId = renderId;
  31597. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31598. }
  31599. if (!this._visibleInstances[renderId]) {
  31600. this._visibleInstances[renderId] = new Array();
  31601. }
  31602. this._visibleInstances[renderId].push(instance);
  31603. return this;
  31604. };
  31605. /**
  31606. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31607. * This means the mesh underlying bounding box and sphere are recomputed.
  31608. * Returns the Mesh.
  31609. */
  31610. Mesh.prototype.refreshBoundingInfo = function () {
  31611. return this._refreshBoundingInfo(false);
  31612. };
  31613. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31614. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31615. return this;
  31616. }
  31617. var data = this._getPositionData(applySkeleton);
  31618. if (data) {
  31619. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31620. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31621. }
  31622. if (this.subMeshes) {
  31623. for (var index = 0; index < this.subMeshes.length; index++) {
  31624. this.subMeshes[index].refreshBoundingInfo();
  31625. }
  31626. }
  31627. this._updateBoundingInfo();
  31628. return this;
  31629. };
  31630. Mesh.prototype._getPositionData = function (applySkeleton) {
  31631. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31632. if (data && applySkeleton && this.skeleton) {
  31633. data = BABYLON.Tools.Slice(data);
  31634. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31635. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31636. if (matricesWeightsData && matricesIndicesData) {
  31637. var needExtras = this.numBoneInfluencers > 4;
  31638. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31639. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31640. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31641. var tempVector = BABYLON.Tmp.Vector3[0];
  31642. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31643. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31644. var matWeightIdx = 0;
  31645. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31646. finalMatrix.reset();
  31647. var inf;
  31648. var weight;
  31649. for (inf = 0; inf < 4; inf++) {
  31650. weight = matricesWeightsData[matWeightIdx + inf];
  31651. if (weight > 0) {
  31652. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31653. finalMatrix.addToSelf(tempMatrix);
  31654. }
  31655. }
  31656. if (needExtras) {
  31657. for (inf = 0; inf < 4; inf++) {
  31658. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31659. if (weight > 0) {
  31660. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31661. finalMatrix.addToSelf(tempMatrix);
  31662. }
  31663. }
  31664. }
  31665. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31666. tempVector.toArray(data, index);
  31667. }
  31668. }
  31669. }
  31670. return data;
  31671. };
  31672. Mesh.prototype._createGlobalSubMesh = function (force) {
  31673. var totalVertices = this.getTotalVertices();
  31674. if (!totalVertices || !this.getIndices()) {
  31675. return null;
  31676. }
  31677. // Check if we need to recreate the submeshes
  31678. if (this.subMeshes && this.subMeshes.length > 0) {
  31679. var ib = this.getIndices();
  31680. if (!ib) {
  31681. return null;
  31682. }
  31683. var totalIndices = ib.length;
  31684. var needToRecreate = false;
  31685. if (force) {
  31686. needToRecreate = true;
  31687. }
  31688. else {
  31689. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31690. var submesh = _a[_i];
  31691. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31692. needToRecreate = true;
  31693. break;
  31694. }
  31695. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31696. needToRecreate = true;
  31697. break;
  31698. }
  31699. }
  31700. }
  31701. if (!needToRecreate) {
  31702. return this.subMeshes[0];
  31703. }
  31704. }
  31705. this.releaseSubMeshes();
  31706. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31707. };
  31708. Mesh.prototype.subdivide = function (count) {
  31709. if (count < 1) {
  31710. return;
  31711. }
  31712. var totalIndices = this.getTotalIndices();
  31713. var subdivisionSize = (totalIndices / count) | 0;
  31714. var offset = 0;
  31715. // Ensure that subdivisionSize is a multiple of 3
  31716. while (subdivisionSize % 3 !== 0) {
  31717. subdivisionSize++;
  31718. }
  31719. this.releaseSubMeshes();
  31720. for (var index = 0; index < count; index++) {
  31721. if (offset >= totalIndices) {
  31722. break;
  31723. }
  31724. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31725. offset += subdivisionSize;
  31726. }
  31727. this.synchronizeInstances();
  31728. };
  31729. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31730. if (updatable === void 0) { updatable = false; }
  31731. if (!this._geometry) {
  31732. var vertexData = new BABYLON.VertexData();
  31733. vertexData.set(data, kind);
  31734. var scene = this.getScene();
  31735. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31736. }
  31737. else {
  31738. this._geometry.setVerticesData(kind, data, updatable, stride);
  31739. }
  31740. return this;
  31741. };
  31742. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31743. if (updatable === void 0) { updatable = true; }
  31744. var vb = this.getVertexBuffer(kind);
  31745. if (!vb || vb.isUpdatable() === updatable) {
  31746. return;
  31747. }
  31748. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31749. };
  31750. /**
  31751. * Sets the mesh VertexBuffer.
  31752. * Returns the Mesh.
  31753. */
  31754. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31755. if (!this._geometry) {
  31756. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31757. }
  31758. this._geometry.setVerticesBuffer(buffer);
  31759. return this;
  31760. };
  31761. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31762. if (!this._geometry) {
  31763. return this;
  31764. }
  31765. if (!makeItUnique) {
  31766. this._geometry.updateVerticesData(kind, data, updateExtends);
  31767. }
  31768. else {
  31769. this.makeGeometryUnique();
  31770. this.updateVerticesData(kind, data, updateExtends, false);
  31771. }
  31772. return this;
  31773. };
  31774. /**
  31775. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31776. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31777. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31778. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31779. * Returns the Mesh.
  31780. */
  31781. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31782. if (computeNormals === void 0) { computeNormals = true; }
  31783. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31784. if (!positions) {
  31785. return this;
  31786. }
  31787. positionFunction(positions);
  31788. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31789. if (computeNormals) {
  31790. var indices = this.getIndices();
  31791. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31792. if (!normals) {
  31793. return this;
  31794. }
  31795. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31796. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31797. }
  31798. return this;
  31799. };
  31800. /**
  31801. * Creates a un-shared specific occurence of the geometry for the mesh.
  31802. * Returns the Mesh.
  31803. */
  31804. Mesh.prototype.makeGeometryUnique = function () {
  31805. if (!this._geometry) {
  31806. return this;
  31807. }
  31808. var oldGeometry = this._geometry;
  31809. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31810. oldGeometry.releaseForMesh(this, true);
  31811. geometry.applyToMesh(this);
  31812. return this;
  31813. };
  31814. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31815. if (totalVertices === void 0) { totalVertices = null; }
  31816. if (updatable === void 0) { updatable = false; }
  31817. if (!this._geometry) {
  31818. var vertexData = new BABYLON.VertexData();
  31819. vertexData.indices = indices;
  31820. var scene = this.getScene();
  31821. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31822. }
  31823. else {
  31824. this._geometry.setIndices(indices, totalVertices, updatable);
  31825. }
  31826. return this;
  31827. };
  31828. /**
  31829. * Update the current index buffer
  31830. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31831. * Returns the Mesh.
  31832. */
  31833. Mesh.prototype.updateIndices = function (indices, offset) {
  31834. if (!this._geometry) {
  31835. return this;
  31836. }
  31837. this._geometry.updateIndices(indices, offset);
  31838. return this;
  31839. };
  31840. /**
  31841. * Invert the geometry to move from a right handed system to a left handed one.
  31842. * Returns the Mesh.
  31843. */
  31844. Mesh.prototype.toLeftHanded = function () {
  31845. if (!this._geometry) {
  31846. return this;
  31847. }
  31848. this._geometry.toLeftHanded();
  31849. return this;
  31850. };
  31851. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31852. if (!this._geometry) {
  31853. return this;
  31854. }
  31855. var engine = this.getScene().getEngine();
  31856. // Wireframe
  31857. var indexToBind;
  31858. if (this._unIndexed) {
  31859. indexToBind = null;
  31860. }
  31861. else {
  31862. switch (fillMode) {
  31863. case BABYLON.Material.PointFillMode:
  31864. indexToBind = null;
  31865. break;
  31866. case BABYLON.Material.WireFrameFillMode:
  31867. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31868. break;
  31869. default:
  31870. case BABYLON.Material.TriangleFillMode:
  31871. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31872. break;
  31873. }
  31874. }
  31875. // VBOs
  31876. this._geometry._bind(effect, indexToBind);
  31877. return this;
  31878. };
  31879. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31880. if (alternate === void 0) { alternate = false; }
  31881. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31882. return this;
  31883. }
  31884. this.onBeforeDrawObservable.notifyObservers(this);
  31885. var scene = this.getScene();
  31886. var engine = scene.getEngine();
  31887. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31888. // or triangles as points
  31889. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31890. }
  31891. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31892. // Triangles as wireframe
  31893. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31894. }
  31895. else {
  31896. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31897. }
  31898. if (scene._isAlternateRenderingEnabled && !alternate) {
  31899. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31900. if (!effect || !scene.activeCamera) {
  31901. return this;
  31902. }
  31903. scene._switchToAlternateCameraConfiguration(true);
  31904. this._effectiveMaterial.bindView(effect);
  31905. this._effectiveMaterial.bindViewProjection(effect);
  31906. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31907. this._draw(subMesh, fillMode, instancesCount, true);
  31908. engine.setViewport(scene.activeCamera.viewport);
  31909. scene._switchToAlternateCameraConfiguration(false);
  31910. this._effectiveMaterial.bindView(effect);
  31911. this._effectiveMaterial.bindViewProjection(effect);
  31912. }
  31913. return this;
  31914. };
  31915. /**
  31916. * Registers for this mesh a javascript function called just before the rendering process.
  31917. * This function is passed the current mesh.
  31918. * Return the Mesh.
  31919. */
  31920. Mesh.prototype.registerBeforeRender = function (func) {
  31921. this.onBeforeRenderObservable.add(func);
  31922. return this;
  31923. };
  31924. /**
  31925. * Disposes a previously registered javascript function called before the rendering.
  31926. * This function is passed the current mesh.
  31927. * Returns the Mesh.
  31928. */
  31929. Mesh.prototype.unregisterBeforeRender = function (func) {
  31930. this.onBeforeRenderObservable.removeCallback(func);
  31931. return this;
  31932. };
  31933. /**
  31934. * Registers for this mesh a javascript function called just after the rendering is complete.
  31935. * This function is passed the current mesh.
  31936. * Returns the Mesh.
  31937. */
  31938. Mesh.prototype.registerAfterRender = function (func) {
  31939. this.onAfterRenderObservable.add(func);
  31940. return this;
  31941. };
  31942. /**
  31943. * Disposes a previously registered javascript function called after the rendering.
  31944. * This function is passed the current mesh.
  31945. * Return the Mesh.
  31946. */
  31947. Mesh.prototype.unregisterAfterRender = function (func) {
  31948. this.onAfterRenderObservable.removeCallback(func);
  31949. return this;
  31950. };
  31951. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31952. var scene = this.getScene();
  31953. this._batchCache.mustReturn = false;
  31954. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31955. this._batchCache.visibleInstances[subMeshId] = null;
  31956. if (this._visibleInstances) {
  31957. var currentRenderId = scene.getRenderId();
  31958. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31959. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31960. var selfRenderId = this._renderId;
  31961. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31962. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31963. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31964. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31965. }
  31966. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31967. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31968. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31969. this._batchCache.mustReturn = true;
  31970. return this._batchCache;
  31971. }
  31972. if (currentRenderId !== selfRenderId) {
  31973. this._batchCache.renderSelf[subMeshId] = false;
  31974. }
  31975. }
  31976. this._renderIdForInstances[subMeshId] = currentRenderId;
  31977. }
  31978. return this._batchCache;
  31979. };
  31980. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31981. var visibleInstances = batch.visibleInstances[subMesh._id];
  31982. if (!visibleInstances) {
  31983. return this;
  31984. }
  31985. var matricesCount = visibleInstances.length + 1;
  31986. var bufferSize = matricesCount * 16 * 4;
  31987. var currentInstancesBufferSize = this._instancesBufferSize;
  31988. var instancesBuffer = this._instancesBuffer;
  31989. while (this._instancesBufferSize < bufferSize) {
  31990. this._instancesBufferSize *= 2;
  31991. }
  31992. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31993. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31994. }
  31995. var offset = 0;
  31996. var instancesCount = 0;
  31997. var world = this.getWorldMatrix();
  31998. if (batch.renderSelf[subMesh._id]) {
  31999. world.copyToArray(this._instancesData, offset);
  32000. offset += 16;
  32001. instancesCount++;
  32002. }
  32003. if (visibleInstances) {
  32004. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32005. var instance = visibleInstances[instanceIndex];
  32006. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32007. offset += 16;
  32008. instancesCount++;
  32009. }
  32010. }
  32011. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32012. if (instancesBuffer) {
  32013. instancesBuffer.dispose();
  32014. }
  32015. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32016. this._instancesBuffer = instancesBuffer;
  32017. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32018. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32019. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32020. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32021. }
  32022. else {
  32023. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32024. }
  32025. this._bind(subMesh, effect, fillMode);
  32026. this._draw(subMesh, fillMode, instancesCount);
  32027. engine.unbindInstanceAttributes();
  32028. return this;
  32029. };
  32030. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32031. var scene = this.getScene();
  32032. var engine = scene.getEngine();
  32033. if (hardwareInstancedRendering) {
  32034. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32035. }
  32036. else {
  32037. if (batch.renderSelf[subMesh._id]) {
  32038. // Draw
  32039. if (onBeforeDraw) {
  32040. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32041. }
  32042. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32043. }
  32044. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32045. if (visibleInstancesForSubMesh) {
  32046. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32047. var instance = visibleInstancesForSubMesh[instanceIndex];
  32048. // World
  32049. var world = instance.getWorldMatrix();
  32050. if (onBeforeDraw) {
  32051. onBeforeDraw(true, world, effectiveMaterial);
  32052. }
  32053. // Draw
  32054. this._draw(subMesh, fillMode);
  32055. }
  32056. }
  32057. }
  32058. return this;
  32059. };
  32060. /**
  32061. * 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
  32062. * @param subMesh defines the subMesh to render
  32063. * @param enableAlphaMode defines if alpha mode can be changed
  32064. * @returns the current mesh
  32065. */
  32066. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32067. this._checkOcclusionQuery();
  32068. if (this._isOccluded) {
  32069. return this;
  32070. }
  32071. var scene = this.getScene();
  32072. // Managing instances
  32073. var batch = this._getInstancesRenderList(subMesh._id);
  32074. if (batch.mustReturn) {
  32075. return this;
  32076. }
  32077. // Checking geometry state
  32078. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32079. return this;
  32080. }
  32081. this.onBeforeRenderObservable.notifyObservers(this);
  32082. var engine = scene.getEngine();
  32083. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32084. // Material
  32085. var material = subMesh.getMaterial();
  32086. if (!material) {
  32087. return this;
  32088. }
  32089. this._effectiveMaterial = material;
  32090. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32091. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32092. return this;
  32093. }
  32094. }
  32095. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32096. return this;
  32097. }
  32098. // Alpha mode
  32099. if (enableAlphaMode) {
  32100. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32101. }
  32102. // Outline - step 1
  32103. var savedDepthWrite = engine.getDepthWrite();
  32104. if (this.renderOutline) {
  32105. engine.setDepthWrite(false);
  32106. scene.getOutlineRenderer().render(subMesh, batch);
  32107. engine.setDepthWrite(savedDepthWrite);
  32108. }
  32109. var effect;
  32110. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32111. effect = subMesh.effect;
  32112. }
  32113. else {
  32114. effect = this._effectiveMaterial.getEffect();
  32115. }
  32116. if (!effect) {
  32117. return this;
  32118. }
  32119. var sideOrientation = this.overrideMaterialSideOrientation;
  32120. if (sideOrientation == null) {
  32121. sideOrientation = this._effectiveMaterial.sideOrientation;
  32122. if (this._getWorldMatrixDeterminant() < 0) {
  32123. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32124. }
  32125. }
  32126. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32127. if (this._effectiveMaterial.forceDepthWrite) {
  32128. engine.setDepthWrite(true);
  32129. }
  32130. // Bind
  32131. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32132. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32133. this._bind(subMesh, effect, fillMode);
  32134. }
  32135. var world = this.getWorldMatrix();
  32136. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32137. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32138. }
  32139. else {
  32140. this._effectiveMaterial.bind(world, this);
  32141. }
  32142. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32143. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32144. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32145. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32146. }
  32147. // Draw
  32148. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32149. // Unbind
  32150. this._effectiveMaterial.unbind();
  32151. // Outline - step 2
  32152. if (this.renderOutline && savedDepthWrite) {
  32153. engine.setDepthWrite(true);
  32154. engine.setColorWrite(false);
  32155. scene.getOutlineRenderer().render(subMesh, batch);
  32156. engine.setColorWrite(true);
  32157. }
  32158. // Overlay
  32159. if (this.renderOverlay) {
  32160. var currentMode = engine.getAlphaMode();
  32161. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32162. scene.getOutlineRenderer().render(subMesh, batch, true);
  32163. engine.setAlphaMode(currentMode);
  32164. }
  32165. this.onAfterRenderObservable.notifyObservers(this);
  32166. return this;
  32167. };
  32168. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32169. if (isInstance && effectiveMaterial) {
  32170. effectiveMaterial.bindOnlyWorldMatrix(world);
  32171. }
  32172. };
  32173. /**
  32174. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32175. */
  32176. Mesh.prototype.getEmittedParticleSystems = function () {
  32177. var results = new Array();
  32178. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32179. var particleSystem = this.getScene().particleSystems[index];
  32180. if (particleSystem.emitter === this) {
  32181. results.push(particleSystem);
  32182. }
  32183. }
  32184. return results;
  32185. };
  32186. /**
  32187. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32188. */
  32189. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32190. var results = new Array();
  32191. var descendants = this.getDescendants();
  32192. descendants.push(this);
  32193. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32194. var particleSystem = this.getScene().particleSystems[index];
  32195. var emitter = particleSystem.emitter;
  32196. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32197. results.push(particleSystem);
  32198. }
  32199. }
  32200. return results;
  32201. };
  32202. /**
  32203. * Normalize matrix weights so that all vertices have a total weight set to 1
  32204. */
  32205. Mesh.prototype.cleanMatrixWeights = function () {
  32206. var epsilon = 1e-3;
  32207. var noInfluenceBoneIndex = 0.0;
  32208. if (this.skeleton) {
  32209. noInfluenceBoneIndex = this.skeleton.bones.length;
  32210. }
  32211. else {
  32212. return;
  32213. }
  32214. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32215. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32216. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32217. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32218. var influencers = this.numBoneInfluencers;
  32219. var size = matricesWeights.length;
  32220. for (var i = 0; i < size; i += 4) {
  32221. var weight = 0.0;
  32222. var firstZeroWeight = -1;
  32223. for (var j = 0; j < 4; j++) {
  32224. var w = matricesWeights[i + j];
  32225. weight += w;
  32226. if (w < epsilon && firstZeroWeight < 0) {
  32227. firstZeroWeight = j;
  32228. }
  32229. }
  32230. if (matricesWeightsExtra) {
  32231. for (var j = 0; j < 4; j++) {
  32232. var w = matricesWeightsExtra[i + j];
  32233. weight += w;
  32234. if (w < epsilon && firstZeroWeight < 0) {
  32235. firstZeroWeight = j + 4;
  32236. }
  32237. }
  32238. }
  32239. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32240. firstZeroWeight = influencers - 1;
  32241. }
  32242. if (weight > epsilon) {
  32243. var mweight = 1.0 / weight;
  32244. for (var j = 0; j < 4; j++) {
  32245. matricesWeights[i + j] *= mweight;
  32246. }
  32247. if (matricesWeightsExtra) {
  32248. for (var j = 0; j < 4; j++) {
  32249. matricesWeightsExtra[i + j] *= mweight;
  32250. }
  32251. }
  32252. }
  32253. else {
  32254. if (firstZeroWeight >= 4) {
  32255. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32256. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32257. }
  32258. else {
  32259. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32260. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32261. }
  32262. }
  32263. }
  32264. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32265. if (matricesIndicesExtra) {
  32266. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32267. }
  32268. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32269. if (matricesWeightsExtra) {
  32270. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32271. }
  32272. };
  32273. Mesh.prototype._checkDelayState = function () {
  32274. var scene = this.getScene();
  32275. if (this._geometry) {
  32276. this._geometry.load(scene);
  32277. }
  32278. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32279. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32280. this._queueLoad(scene);
  32281. }
  32282. return this;
  32283. };
  32284. Mesh.prototype._queueLoad = function (scene) {
  32285. var _this = this;
  32286. scene._addPendingData(this);
  32287. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32288. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32289. if (data instanceof ArrayBuffer) {
  32290. _this._delayLoadingFunction(data, _this);
  32291. }
  32292. else {
  32293. _this._delayLoadingFunction(JSON.parse(data), _this);
  32294. }
  32295. _this.instances.forEach(function (instance) {
  32296. instance._syncSubMeshes();
  32297. });
  32298. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32299. scene._removePendingData(_this);
  32300. }, function () { }, scene.database, getBinaryData);
  32301. return this;
  32302. };
  32303. /**
  32304. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32305. */
  32306. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32307. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32308. return false;
  32309. }
  32310. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32311. return false;
  32312. }
  32313. this._checkDelayState();
  32314. return true;
  32315. };
  32316. /**
  32317. * Sets the mesh material by the material or multiMaterial `id` property.
  32318. * The material `id` is a string identifying the material or the multiMaterial.
  32319. * This method returns the Mesh.
  32320. */
  32321. Mesh.prototype.setMaterialByID = function (id) {
  32322. var materials = this.getScene().materials;
  32323. var index;
  32324. for (index = materials.length - 1; index > -1; index--) {
  32325. if (materials[index].id === id) {
  32326. this.material = materials[index];
  32327. return this;
  32328. }
  32329. }
  32330. // Multi
  32331. var multiMaterials = this.getScene().multiMaterials;
  32332. for (index = multiMaterials.length - 1; index > -1; index--) {
  32333. if (multiMaterials[index].id === id) {
  32334. this.material = multiMaterials[index];
  32335. return this;
  32336. }
  32337. }
  32338. return this;
  32339. };
  32340. /**
  32341. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32342. */
  32343. Mesh.prototype.getAnimatables = function () {
  32344. var results = new Array();
  32345. if (this.material) {
  32346. results.push(this.material);
  32347. }
  32348. if (this.skeleton) {
  32349. results.push(this.skeleton);
  32350. }
  32351. return results;
  32352. };
  32353. /**
  32354. * Modifies the mesh geometry according to the passed transformation matrix.
  32355. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32356. * The mesh normals are modified accordingly the same transformation.
  32357. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32358. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32359. * Returns the Mesh.
  32360. */
  32361. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32362. // Position
  32363. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32364. return this;
  32365. }
  32366. var submeshes = this.subMeshes.splice(0);
  32367. this._resetPointsArrayCache();
  32368. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32369. var temp = new Array();
  32370. var index;
  32371. for (index = 0; index < data.length; index += 3) {
  32372. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32373. }
  32374. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32375. // Normals
  32376. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32377. return this;
  32378. }
  32379. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32380. temp = [];
  32381. for (index = 0; index < data.length; index += 3) {
  32382. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32383. }
  32384. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32385. // flip faces?
  32386. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32387. this.flipFaces();
  32388. }
  32389. // Restore submeshes
  32390. this.releaseSubMeshes();
  32391. this.subMeshes = submeshes;
  32392. return this;
  32393. };
  32394. /**
  32395. * Modifies the mesh geometry according to its own current World Matrix.
  32396. * The mesh World Matrix is then reset.
  32397. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32398. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32399. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32400. * Returns the Mesh.
  32401. */
  32402. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32403. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32404. this.scaling.copyFromFloats(1, 1, 1);
  32405. this.position.copyFromFloats(0, 0, 0);
  32406. this.rotation.copyFromFloats(0, 0, 0);
  32407. //only if quaternion is already set
  32408. if (this.rotationQuaternion) {
  32409. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32410. }
  32411. this._worldMatrix = BABYLON.Matrix.Identity();
  32412. return this;
  32413. };
  32414. Object.defineProperty(Mesh.prototype, "_positions", {
  32415. // Cache
  32416. get: function () {
  32417. if (this._geometry) {
  32418. return this._geometry._positions;
  32419. }
  32420. return null;
  32421. },
  32422. enumerable: true,
  32423. configurable: true
  32424. });
  32425. Mesh.prototype._resetPointsArrayCache = function () {
  32426. if (this._geometry) {
  32427. this._geometry._resetPointsArrayCache();
  32428. }
  32429. return this;
  32430. };
  32431. Mesh.prototype._generatePointsArray = function () {
  32432. if (this._geometry) {
  32433. return this._geometry._generatePointsArray();
  32434. }
  32435. return false;
  32436. };
  32437. /**
  32438. * Returns a new Mesh object generated from the current mesh properties.
  32439. * This method must not get confused with createInstance().
  32440. * The parameter `name` is a string, the name given to the new mesh.
  32441. * The optional parameter `newParent` can be any Node object (default `null`).
  32442. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32443. * 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.
  32444. */
  32445. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32446. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32447. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32448. };
  32449. /**
  32450. * Releases resources associated with this mesh.
  32451. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32452. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32453. */
  32454. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32455. var _this = this;
  32456. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32457. this.morphTargetManager = null;
  32458. if (this._geometry) {
  32459. this._geometry.releaseForMesh(this, true);
  32460. }
  32461. // Sources
  32462. var meshes = this.getScene().meshes;
  32463. meshes.forEach(function (abstractMesh) {
  32464. var mesh = abstractMesh;
  32465. if (mesh._source && mesh._source === _this) {
  32466. mesh._source = null;
  32467. }
  32468. });
  32469. this._source = null;
  32470. // Instances
  32471. if (this._instancesBuffer) {
  32472. this._instancesBuffer.dispose();
  32473. this._instancesBuffer = null;
  32474. }
  32475. while (this.instances.length) {
  32476. this.instances[0].dispose();
  32477. }
  32478. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32479. };
  32480. /**
  32481. * Modifies the mesh geometry according to a displacement map.
  32482. * 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.
  32483. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32484. * This method returns nothing.
  32485. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32486. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32487. * 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.
  32488. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32489. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32490. *
  32491. * Returns the Mesh.
  32492. */
  32493. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32494. var _this = this;
  32495. var scene = this.getScene();
  32496. var onload = function (img) {
  32497. // Getting height map data
  32498. var canvas = document.createElement("canvas");
  32499. var context = canvas.getContext("2d");
  32500. var heightMapWidth = img.width;
  32501. var heightMapHeight = img.height;
  32502. canvas.width = heightMapWidth;
  32503. canvas.height = heightMapHeight;
  32504. context.drawImage(img, 0, 0);
  32505. // Create VertexData from map data
  32506. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32507. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32508. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32509. //execute success callback, if set
  32510. if (onSuccess) {
  32511. onSuccess(_this);
  32512. }
  32513. };
  32514. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32515. return this;
  32516. };
  32517. /**
  32518. * Modifies the mesh geometry according to a displacementMap buffer.
  32519. * 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.
  32520. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32521. * This method returns nothing.
  32522. * 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.
  32523. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32524. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32525. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32526. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32527. *
  32528. * Returns the Mesh.
  32529. */
  32530. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32531. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32532. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32533. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32534. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32535. return this;
  32536. }
  32537. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32538. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32539. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32540. var position = BABYLON.Vector3.Zero();
  32541. var normal = BABYLON.Vector3.Zero();
  32542. var uv = BABYLON.Vector2.Zero();
  32543. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32544. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32545. for (var index = 0; index < positions.length; index += 3) {
  32546. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32547. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32548. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32549. // Compute height
  32550. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32551. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32552. var pos = (u + v * heightMapWidth) * 4;
  32553. var r = buffer[pos] / 255.0;
  32554. var g = buffer[pos + 1] / 255.0;
  32555. var b = buffer[pos + 2] / 255.0;
  32556. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32557. normal.normalize();
  32558. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32559. position = position.add(normal);
  32560. position.toArray(positions, index);
  32561. }
  32562. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32563. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32564. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32565. return this;
  32566. };
  32567. /**
  32568. * Modify the mesh to get a flat shading rendering.
  32569. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32570. * This method returns the Mesh.
  32571. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32572. */
  32573. Mesh.prototype.convertToFlatShadedMesh = function () {
  32574. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32575. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32576. var kinds = this.getVerticesDataKinds();
  32577. var vbs = {};
  32578. var data = {};
  32579. var newdata = {};
  32580. var updatableNormals = false;
  32581. var kindIndex;
  32582. var kind;
  32583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32584. kind = kinds[kindIndex];
  32585. var vertexBuffer = this.getVertexBuffer(kind);
  32586. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32587. updatableNormals = vertexBuffer.isUpdatable();
  32588. kinds.splice(kindIndex, 1);
  32589. kindIndex--;
  32590. continue;
  32591. }
  32592. vbs[kind] = vertexBuffer;
  32593. data[kind] = vbs[kind].getData();
  32594. newdata[kind] = [];
  32595. }
  32596. // Save previous submeshes
  32597. var previousSubmeshes = this.subMeshes.slice(0);
  32598. var indices = this.getIndices();
  32599. var totalIndices = this.getTotalIndices();
  32600. // Generating unique vertices per face
  32601. var index;
  32602. for (index = 0; index < totalIndices; index++) {
  32603. var vertexIndex = indices[index];
  32604. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32605. kind = kinds[kindIndex];
  32606. var stride = vbs[kind].getStrideSize();
  32607. for (var offset = 0; offset < stride; offset++) {
  32608. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32609. }
  32610. }
  32611. }
  32612. // Updating faces & normal
  32613. var normals = [];
  32614. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32615. for (index = 0; index < totalIndices; index += 3) {
  32616. indices[index] = index;
  32617. indices[index + 1] = index + 1;
  32618. indices[index + 2] = index + 2;
  32619. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32620. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32621. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32622. var p1p2 = p1.subtract(p2);
  32623. var p3p2 = p3.subtract(p2);
  32624. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32625. // Store same normals for every vertex
  32626. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32627. normals.push(normal.x);
  32628. normals.push(normal.y);
  32629. normals.push(normal.z);
  32630. }
  32631. }
  32632. this.setIndices(indices);
  32633. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32634. // Updating vertex buffers
  32635. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32636. kind = kinds[kindIndex];
  32637. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32638. }
  32639. // Updating submeshes
  32640. this.releaseSubMeshes();
  32641. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32642. var previousOne = previousSubmeshes[submeshIndex];
  32643. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32644. }
  32645. this.synchronizeInstances();
  32646. return this;
  32647. };
  32648. /**
  32649. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32650. * In other words, more vertices, no more indices and a single bigger VBO.
  32651. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32652. * Returns the Mesh.
  32653. */
  32654. Mesh.prototype.convertToUnIndexedMesh = function () {
  32655. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32656. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32657. var kinds = this.getVerticesDataKinds();
  32658. var vbs = {};
  32659. var data = {};
  32660. var newdata = {};
  32661. var kindIndex;
  32662. var kind;
  32663. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32664. kind = kinds[kindIndex];
  32665. var vertexBuffer = this.getVertexBuffer(kind);
  32666. vbs[kind] = vertexBuffer;
  32667. data[kind] = vbs[kind].getData();
  32668. newdata[kind] = [];
  32669. }
  32670. // Save previous submeshes
  32671. var previousSubmeshes = this.subMeshes.slice(0);
  32672. var indices = this.getIndices();
  32673. var totalIndices = this.getTotalIndices();
  32674. // Generating unique vertices per face
  32675. var index;
  32676. for (index = 0; index < totalIndices; index++) {
  32677. var vertexIndex = indices[index];
  32678. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32679. kind = kinds[kindIndex];
  32680. var stride = vbs[kind].getStrideSize();
  32681. for (var offset = 0; offset < stride; offset++) {
  32682. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32683. }
  32684. }
  32685. }
  32686. // Updating indices
  32687. for (index = 0; index < totalIndices; index += 3) {
  32688. indices[index] = index;
  32689. indices[index + 1] = index + 1;
  32690. indices[index + 2] = index + 2;
  32691. }
  32692. this.setIndices(indices);
  32693. // Updating vertex buffers
  32694. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32695. kind = kinds[kindIndex];
  32696. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32697. }
  32698. // Updating submeshes
  32699. this.releaseSubMeshes();
  32700. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32701. var previousOne = previousSubmeshes[submeshIndex];
  32702. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32703. }
  32704. this._unIndexed = true;
  32705. this.synchronizeInstances();
  32706. return this;
  32707. };
  32708. /**
  32709. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32710. * This method returns the Mesh.
  32711. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32712. */
  32713. Mesh.prototype.flipFaces = function (flipNormals) {
  32714. if (flipNormals === void 0) { flipNormals = false; }
  32715. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32716. var i;
  32717. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32718. for (i = 0; i < vertex_data.normals.length; i++) {
  32719. vertex_data.normals[i] *= -1;
  32720. }
  32721. }
  32722. if (vertex_data.indices) {
  32723. var temp;
  32724. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32725. // reassign indices
  32726. temp = vertex_data.indices[i + 1];
  32727. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32728. vertex_data.indices[i + 2] = temp;
  32729. }
  32730. }
  32731. vertex_data.applyToMesh(this);
  32732. return this;
  32733. };
  32734. // Instances
  32735. /**
  32736. * Creates a new InstancedMesh object from the mesh model.
  32737. * An instance shares the same properties and the same material than its model.
  32738. * Only these properties of each instance can then be set individually :
  32739. * - position
  32740. * - rotation
  32741. * - rotationQuaternion
  32742. * - setPivotMatrix
  32743. * - scaling
  32744. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32745. * Warning : this method is not supported for Line mesh and LineSystem
  32746. */
  32747. Mesh.prototype.createInstance = function (name) {
  32748. return new BABYLON.InstancedMesh(name, this);
  32749. };
  32750. /**
  32751. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32752. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32753. * This method returns the Mesh.
  32754. */
  32755. Mesh.prototype.synchronizeInstances = function () {
  32756. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32757. var instance = this.instances[instanceIndex];
  32758. instance._syncSubMeshes();
  32759. }
  32760. return this;
  32761. };
  32762. /**
  32763. * Simplify the mesh according to the given array of settings.
  32764. * Function will return immediately and will simplify async. It returns the Mesh.
  32765. * @param settings a collection of simplification settings.
  32766. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32767. * @param type the type of simplification to run.
  32768. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32769. */
  32770. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32771. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32772. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32773. this.getScene().simplificationQueue.addTask({
  32774. settings: settings,
  32775. parallelProcessing: parallelProcessing,
  32776. mesh: this,
  32777. simplificationType: simplificationType,
  32778. successCallback: successCallback
  32779. });
  32780. return this;
  32781. };
  32782. /**
  32783. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32784. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32785. * This should be used together with the simplification to avoid disappearing triangles.
  32786. * Returns the Mesh.
  32787. * @param successCallback an optional success callback to be called after the optimization finished.
  32788. */
  32789. Mesh.prototype.optimizeIndices = function (successCallback) {
  32790. var _this = this;
  32791. var indices = this.getIndices();
  32792. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32793. if (!positions || !indices) {
  32794. return this;
  32795. }
  32796. var vectorPositions = new Array();
  32797. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32798. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32799. }
  32800. var dupes = new Array();
  32801. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32802. var realPos = vectorPositions.length - 1 - iteration;
  32803. var testedPosition = vectorPositions[realPos];
  32804. for (var j = 0; j < realPos; ++j) {
  32805. var againstPosition = vectorPositions[j];
  32806. if (testedPosition.equals(againstPosition)) {
  32807. dupes[realPos] = j;
  32808. break;
  32809. }
  32810. }
  32811. }, function () {
  32812. for (var i = 0; i < indices.length; ++i) {
  32813. indices[i] = dupes[indices[i]] || indices[i];
  32814. }
  32815. //indices are now reordered
  32816. var originalSubMeshes = _this.subMeshes.slice(0);
  32817. _this.setIndices(indices);
  32818. _this.subMeshes = originalSubMeshes;
  32819. if (successCallback) {
  32820. successCallback(_this);
  32821. }
  32822. });
  32823. return this;
  32824. };
  32825. Mesh.prototype.serialize = function (serializationObject) {
  32826. serializationObject.name = this.name;
  32827. serializationObject.id = this.id;
  32828. serializationObject.type = this.getClassName();
  32829. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32830. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32831. }
  32832. serializationObject.position = this.position.asArray();
  32833. if (this.rotationQuaternion) {
  32834. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32835. }
  32836. else if (this.rotation) {
  32837. serializationObject.rotation = this.rotation.asArray();
  32838. }
  32839. serializationObject.scaling = this.scaling.asArray();
  32840. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32841. serializationObject.isEnabled = this.isEnabled(false);
  32842. serializationObject.isVisible = this.isVisible;
  32843. serializationObject.infiniteDistance = this.infiniteDistance;
  32844. serializationObject.pickable = this.isPickable;
  32845. serializationObject.receiveShadows = this.receiveShadows;
  32846. serializationObject.billboardMode = this.billboardMode;
  32847. serializationObject.visibility = this.visibility;
  32848. serializationObject.checkCollisions = this.checkCollisions;
  32849. serializationObject.isBlocker = this.isBlocker;
  32850. // Parent
  32851. if (this.parent) {
  32852. serializationObject.parentId = this.parent.id;
  32853. }
  32854. // Geometry
  32855. serializationObject.isUnIndexed = this.isUnIndexed;
  32856. var geometry = this._geometry;
  32857. if (geometry) {
  32858. var geometryId = geometry.id;
  32859. serializationObject.geometryId = geometryId;
  32860. // SubMeshes
  32861. serializationObject.subMeshes = [];
  32862. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32863. var subMesh = this.subMeshes[subIndex];
  32864. serializationObject.subMeshes.push({
  32865. materialIndex: subMesh.materialIndex,
  32866. verticesStart: subMesh.verticesStart,
  32867. verticesCount: subMesh.verticesCount,
  32868. indexStart: subMesh.indexStart,
  32869. indexCount: subMesh.indexCount
  32870. });
  32871. }
  32872. }
  32873. // Material
  32874. if (this.material) {
  32875. serializationObject.materialId = this.material.id;
  32876. }
  32877. else {
  32878. this.material = null;
  32879. }
  32880. // Morph targets
  32881. if (this.morphTargetManager) {
  32882. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32883. }
  32884. // Skeleton
  32885. if (this.skeleton) {
  32886. serializationObject.skeletonId = this.skeleton.id;
  32887. }
  32888. // Physics
  32889. //TODO implement correct serialization for physics impostors.
  32890. var impostor = this.getPhysicsImpostor();
  32891. if (impostor) {
  32892. serializationObject.physicsMass = impostor.getParam("mass");
  32893. serializationObject.physicsFriction = impostor.getParam("friction");
  32894. serializationObject.physicsRestitution = impostor.getParam("mass");
  32895. serializationObject.physicsImpostor = impostor.type;
  32896. }
  32897. // Metadata
  32898. if (this.metadata) {
  32899. serializationObject.metadata = this.metadata;
  32900. }
  32901. // Instances
  32902. serializationObject.instances = [];
  32903. for (var index = 0; index < this.instances.length; index++) {
  32904. var instance = this.instances[index];
  32905. var serializationInstance = {
  32906. name: instance.name,
  32907. id: instance.id,
  32908. position: instance.position.asArray(),
  32909. scaling: instance.scaling.asArray()
  32910. };
  32911. if (instance.rotationQuaternion) {
  32912. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32913. }
  32914. else if (instance.rotation) {
  32915. serializationInstance.rotation = instance.rotation.asArray();
  32916. }
  32917. serializationObject.instances.push(serializationInstance);
  32918. // Animations
  32919. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32920. serializationInstance.ranges = instance.serializeAnimationRanges();
  32921. }
  32922. //
  32923. // Animations
  32924. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32925. serializationObject.ranges = this.serializeAnimationRanges();
  32926. // Layer mask
  32927. serializationObject.layerMask = this.layerMask;
  32928. // Alpha
  32929. serializationObject.alphaIndex = this.alphaIndex;
  32930. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32931. // Overlay
  32932. serializationObject.overlayAlpha = this.overlayAlpha;
  32933. serializationObject.overlayColor = this.overlayColor.asArray();
  32934. serializationObject.renderOverlay = this.renderOverlay;
  32935. // Fog
  32936. serializationObject.applyFog = this.applyFog;
  32937. // Action Manager
  32938. if (this.actionManager) {
  32939. serializationObject.actions = this.actionManager.serialize(this.name);
  32940. }
  32941. };
  32942. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32943. if (!this.geometry) {
  32944. return;
  32945. }
  32946. this._markSubMeshesAsAttributesDirty();
  32947. var morphTargetManager = this._morphTargetManager;
  32948. if (morphTargetManager && morphTargetManager.vertexCount) {
  32949. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32950. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32951. this.morphTargetManager = null;
  32952. return;
  32953. }
  32954. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32955. var morphTarget = morphTargetManager.getActiveTarget(index);
  32956. var positions = morphTarget.getPositions();
  32957. if (!positions) {
  32958. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32959. return;
  32960. }
  32961. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32962. var normals = morphTarget.getNormals();
  32963. if (normals) {
  32964. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32965. }
  32966. var tangents = morphTarget.getTangents();
  32967. if (tangents) {
  32968. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32969. }
  32970. }
  32971. }
  32972. else {
  32973. var index = 0;
  32974. // Positions
  32975. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32976. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32977. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32978. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32979. }
  32980. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32981. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32982. }
  32983. index++;
  32984. }
  32985. }
  32986. };
  32987. // Statics
  32988. /**
  32989. * Returns a new Mesh object parsed from the source provided.
  32990. * The parameter `parsedMesh` is the source.
  32991. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32992. */
  32993. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32994. var mesh;
  32995. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32996. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32997. }
  32998. else {
  32999. mesh = new Mesh(parsedMesh.name, scene);
  33000. }
  33001. mesh.id = parsedMesh.id;
  33002. if (BABYLON.Tags) {
  33003. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33004. }
  33005. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33006. if (parsedMesh.metadata !== undefined) {
  33007. mesh.metadata = parsedMesh.metadata;
  33008. }
  33009. if (parsedMesh.rotationQuaternion) {
  33010. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33011. }
  33012. else if (parsedMesh.rotation) {
  33013. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33014. }
  33015. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33016. if (parsedMesh.localMatrix) {
  33017. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33018. }
  33019. else if (parsedMesh.pivotMatrix) {
  33020. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33021. }
  33022. mesh.setEnabled(parsedMesh.isEnabled);
  33023. mesh.isVisible = parsedMesh.isVisible;
  33024. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33025. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33026. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33027. if (parsedMesh.applyFog !== undefined) {
  33028. mesh.applyFog = parsedMesh.applyFog;
  33029. }
  33030. if (parsedMesh.pickable !== undefined) {
  33031. mesh.isPickable = parsedMesh.pickable;
  33032. }
  33033. if (parsedMesh.alphaIndex !== undefined) {
  33034. mesh.alphaIndex = parsedMesh.alphaIndex;
  33035. }
  33036. mesh.receiveShadows = parsedMesh.receiveShadows;
  33037. mesh.billboardMode = parsedMesh.billboardMode;
  33038. if (parsedMesh.visibility !== undefined) {
  33039. mesh.visibility = parsedMesh.visibility;
  33040. }
  33041. mesh.checkCollisions = parsedMesh.checkCollisions;
  33042. if (parsedMesh.isBlocker !== undefined) {
  33043. mesh.isBlocker = parsedMesh.isBlocker;
  33044. }
  33045. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33046. // freezeWorldMatrix
  33047. if (parsedMesh.freezeWorldMatrix) {
  33048. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33049. }
  33050. // Parent
  33051. if (parsedMesh.parentId) {
  33052. mesh._waitingParentId = parsedMesh.parentId;
  33053. }
  33054. // Actions
  33055. if (parsedMesh.actions !== undefined) {
  33056. mesh._waitingActions = parsedMesh.actions;
  33057. }
  33058. // Overlay
  33059. if (parsedMesh.overlayAlpha !== undefined) {
  33060. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33061. }
  33062. if (parsedMesh.overlayColor !== undefined) {
  33063. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33064. }
  33065. if (parsedMesh.renderOverlay !== undefined) {
  33066. mesh.renderOverlay = parsedMesh.renderOverlay;
  33067. }
  33068. // Geometry
  33069. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33070. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33071. if (parsedMesh.delayLoadingFile) {
  33072. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33073. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33074. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33075. if (parsedMesh._binaryInfo) {
  33076. mesh._binaryInfo = parsedMesh._binaryInfo;
  33077. }
  33078. mesh._delayInfo = [];
  33079. if (parsedMesh.hasUVs) {
  33080. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33081. }
  33082. if (parsedMesh.hasUVs2) {
  33083. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33084. }
  33085. if (parsedMesh.hasUVs3) {
  33086. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33087. }
  33088. if (parsedMesh.hasUVs4) {
  33089. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33090. }
  33091. if (parsedMesh.hasUVs5) {
  33092. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33093. }
  33094. if (parsedMesh.hasUVs6) {
  33095. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33096. }
  33097. if (parsedMesh.hasColors) {
  33098. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33099. }
  33100. if (parsedMesh.hasMatricesIndices) {
  33101. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33102. }
  33103. if (parsedMesh.hasMatricesWeights) {
  33104. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33105. }
  33106. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33107. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33108. mesh._checkDelayState();
  33109. }
  33110. }
  33111. else {
  33112. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33113. }
  33114. // Material
  33115. if (parsedMesh.materialId) {
  33116. mesh.setMaterialByID(parsedMesh.materialId);
  33117. }
  33118. else {
  33119. mesh.material = null;
  33120. }
  33121. // Morph targets
  33122. if (parsedMesh.morphTargetManagerId > -1) {
  33123. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33124. }
  33125. // Skeleton
  33126. if (parsedMesh.skeletonId > -1) {
  33127. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33128. if (parsedMesh.numBoneInfluencers) {
  33129. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33130. }
  33131. }
  33132. // Animations
  33133. if (parsedMesh.animations) {
  33134. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33135. var parsedAnimation = parsedMesh.animations[animationIndex];
  33136. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33137. }
  33138. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33139. }
  33140. if (parsedMesh.autoAnimate) {
  33141. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33142. }
  33143. // Layer Mask
  33144. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33145. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33146. }
  33147. else {
  33148. mesh.layerMask = 0x0FFFFFFF;
  33149. }
  33150. // Physics
  33151. if (parsedMesh.physicsImpostor) {
  33152. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33153. mass: parsedMesh.physicsMass,
  33154. friction: parsedMesh.physicsFriction,
  33155. restitution: parsedMesh.physicsRestitution
  33156. }, scene);
  33157. }
  33158. // Instances
  33159. if (parsedMesh.instances) {
  33160. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33161. var parsedInstance = parsedMesh.instances[index];
  33162. var instance = mesh.createInstance(parsedInstance.name);
  33163. if (parsedInstance.id) {
  33164. instance.id = parsedInstance.id;
  33165. }
  33166. if (BABYLON.Tags) {
  33167. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33168. }
  33169. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33170. if (parsedInstance.parentId) {
  33171. instance._waitingParentId = parsedInstance.parentId;
  33172. }
  33173. if (parsedInstance.rotationQuaternion) {
  33174. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33175. }
  33176. else if (parsedInstance.rotation) {
  33177. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33178. }
  33179. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33180. instance.checkCollisions = mesh.checkCollisions;
  33181. if (parsedMesh.animations) {
  33182. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33183. parsedAnimation = parsedMesh.animations[animationIndex];
  33184. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33185. }
  33186. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33187. if (parsedMesh.autoAnimate) {
  33188. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33189. }
  33190. }
  33191. }
  33192. }
  33193. return mesh;
  33194. };
  33195. /**
  33196. * Creates a ribbon mesh.
  33197. * Please consider using the same method from the MeshBuilder class instead.
  33198. * 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.
  33199. *
  33200. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33201. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33202. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33203. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33204. * 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.
  33205. * 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.
  33206. * 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
  33207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33208. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33210. */
  33211. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33212. if (closeArray === void 0) { closeArray = false; }
  33213. if (updatable === void 0) { updatable = false; }
  33214. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33215. pathArray: pathArray,
  33216. closeArray: closeArray,
  33217. closePath: closePath,
  33218. offset: offset,
  33219. updatable: updatable,
  33220. sideOrientation: sideOrientation,
  33221. instance: instance
  33222. }, scene);
  33223. };
  33224. /**
  33225. * Creates a plane polygonal mesh. By default, this is a disc.
  33226. * Please consider using the same method from the MeshBuilder class instead.
  33227. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33228. * 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.
  33229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33230. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33232. */
  33233. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33234. if (scene === void 0) { scene = null; }
  33235. var options = {
  33236. radius: radius,
  33237. tessellation: tessellation,
  33238. sideOrientation: sideOrientation,
  33239. updatable: updatable
  33240. };
  33241. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33242. };
  33243. /**
  33244. * Creates a box mesh.
  33245. * Please consider using the same method from the MeshBuilder class instead.
  33246. * The parameter `size` sets the size (float) of each box side (default 1).
  33247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33248. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33250. */
  33251. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33252. if (scene === void 0) { scene = null; }
  33253. var options = {
  33254. size: size,
  33255. sideOrientation: sideOrientation,
  33256. updatable: updatable
  33257. };
  33258. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33259. };
  33260. /**
  33261. * Creates a sphere mesh.
  33262. * Please consider using the same method from the MeshBuilder class instead.
  33263. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33264. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33266. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33268. */
  33269. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33270. var options = {
  33271. segments: segments,
  33272. diameterX: diameter,
  33273. diameterY: diameter,
  33274. diameterZ: diameter,
  33275. sideOrientation: sideOrientation,
  33276. updatable: updatable
  33277. };
  33278. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33279. };
  33280. /**
  33281. * Creates a cylinder or a cone mesh.
  33282. * Please consider using the same method from the MeshBuilder class instead.
  33283. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33284. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33285. * 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.
  33286. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33287. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33289. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33291. */
  33292. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33293. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33294. if (scene !== undefined) {
  33295. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33296. updatable = scene;
  33297. }
  33298. scene = subdivisions;
  33299. subdivisions = 1;
  33300. }
  33301. var options = {
  33302. height: height,
  33303. diameterTop: diameterTop,
  33304. diameterBottom: diameterBottom,
  33305. tessellation: tessellation,
  33306. subdivisions: subdivisions,
  33307. sideOrientation: sideOrientation,
  33308. updatable: updatable
  33309. };
  33310. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33311. };
  33312. // Torus (Code from SharpDX.org)
  33313. /**
  33314. * Creates a torus mesh.
  33315. * Please consider using the same method from the MeshBuilder class instead.
  33316. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33317. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33318. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33320. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33322. */
  33323. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33324. var options = {
  33325. diameter: diameter,
  33326. thickness: thickness,
  33327. tessellation: tessellation,
  33328. sideOrientation: sideOrientation,
  33329. updatable: updatable
  33330. };
  33331. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33332. };
  33333. /**
  33334. * Creates a torus knot mesh.
  33335. * Please consider using the same method from the MeshBuilder class instead.
  33336. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33337. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33338. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33339. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33341. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33343. */
  33344. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33345. var options = {
  33346. radius: radius,
  33347. tube: tube,
  33348. radialSegments: radialSegments,
  33349. tubularSegments: tubularSegments,
  33350. p: p,
  33351. q: q,
  33352. sideOrientation: sideOrientation,
  33353. updatable: updatable
  33354. };
  33355. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33356. };
  33357. /**
  33358. * Creates a line mesh.
  33359. * Please consider using the same method from the MeshBuilder class instead.
  33360. * 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.
  33361. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33362. * The parameter `points` is an array successive Vector3.
  33363. * 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
  33364. * When updating an instance, remember that only point positions can change, not the number of points.
  33365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33366. */
  33367. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33368. if (scene === void 0) { scene = null; }
  33369. if (updatable === void 0) { updatable = false; }
  33370. if (instance === void 0) { instance = null; }
  33371. var options = {
  33372. points: points,
  33373. updatable: updatable,
  33374. instance: instance
  33375. };
  33376. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33377. };
  33378. /**
  33379. * Creates a dashed line mesh.
  33380. * Please consider using the same method from the MeshBuilder class instead.
  33381. * 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.
  33382. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33383. * The parameter `points` is an array successive Vector3.
  33384. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33385. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33386. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33387. * 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
  33388. * When updating an instance, remember that only point positions can change, not the number of points.
  33389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33390. */
  33391. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33392. if (scene === void 0) { scene = null; }
  33393. var options = {
  33394. points: points,
  33395. dashSize: dashSize,
  33396. gapSize: gapSize,
  33397. dashNb: dashNb,
  33398. updatable: updatable,
  33399. instance: instance
  33400. };
  33401. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33402. };
  33403. /**
  33404. * Creates a polygon mesh.
  33405. * Please consider using the same method from the MeshBuilder class instead.
  33406. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33407. * 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.
  33408. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33410. * Remember you can only change the shape positions, not their number when updating a polygon.
  33411. */
  33412. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33413. var options = {
  33414. shape: shape,
  33415. holes: holes,
  33416. updatable: updatable,
  33417. sideOrientation: sideOrientation
  33418. };
  33419. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33420. };
  33421. /**
  33422. * Creates an extruded polygon mesh, with depth in the Y direction.
  33423. * Please consider using the same method from the MeshBuilder class instead.
  33424. */
  33425. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33426. var options = {
  33427. shape: shape,
  33428. holes: holes,
  33429. depth: depth,
  33430. updatable: updatable,
  33431. sideOrientation: sideOrientation
  33432. };
  33433. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33434. };
  33435. /**
  33436. * Creates an extruded shape mesh.
  33437. * 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.
  33438. * Please consider using the same method from the MeshBuilder class instead.
  33439. *
  33440. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33441. * 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
  33442. * extruded along the Z axis.
  33443. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33444. * 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.
  33445. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33446. * 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
  33447. * 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
  33448. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33450. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33452. */
  33453. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33454. if (scene === void 0) { scene = null; }
  33455. var options = {
  33456. shape: shape,
  33457. path: path,
  33458. scale: scale,
  33459. rotation: rotation,
  33460. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33461. sideOrientation: sideOrientation,
  33462. instance: instance,
  33463. updatable: updatable
  33464. };
  33465. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33466. };
  33467. /**
  33468. * Creates an custom extruded shape mesh.
  33469. * 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.
  33470. * Please consider using the same method from the MeshBuilder class instead.
  33471. *
  33472. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33473. * 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
  33474. * extruded along the Z axis.
  33475. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33476. * 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
  33477. * and the distance of this point from the begining of the path :
  33478. * ```javascript
  33479. * var rotationFunction = function(i, distance) {
  33480. * // do things
  33481. * return rotationValue; }
  33482. * ```
  33483. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33484. * 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
  33485. * and the distance of this point from the begining of the path :
  33486. * ```javascript
  33487. * var scaleFunction = function(i, distance) {
  33488. * // do things
  33489. * return scaleValue;}
  33490. * ```
  33491. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33492. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33493. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33494. * 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
  33495. * 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
  33496. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33498. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33500. */
  33501. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33502. var options = {
  33503. shape: shape,
  33504. path: path,
  33505. scaleFunction: scaleFunction,
  33506. rotationFunction: rotationFunction,
  33507. ribbonCloseArray: ribbonCloseArray,
  33508. ribbonClosePath: ribbonClosePath,
  33509. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33510. sideOrientation: sideOrientation,
  33511. instance: instance,
  33512. updatable: updatable
  33513. };
  33514. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33515. };
  33516. /**
  33517. * Creates lathe mesh.
  33518. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33519. * Please consider using the same method from the MeshBuilder class instead.
  33520. * 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
  33521. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33522. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33523. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33524. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33525. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33527. */
  33528. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33529. var options = {
  33530. shape: shape,
  33531. radius: radius,
  33532. tessellation: tessellation,
  33533. sideOrientation: sideOrientation,
  33534. updatable: updatable
  33535. };
  33536. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33537. };
  33538. /**
  33539. * Creates a plane mesh.
  33540. * Please consider using the same method from the MeshBuilder class instead.
  33541. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33542. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33543. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33545. */
  33546. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33547. var options = {
  33548. size: size,
  33549. width: size,
  33550. height: size,
  33551. sideOrientation: sideOrientation,
  33552. updatable: updatable
  33553. };
  33554. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33555. };
  33556. /**
  33557. * Creates a ground mesh.
  33558. * Please consider using the same method from the MeshBuilder class instead.
  33559. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33560. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33562. */
  33563. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33564. var options = {
  33565. width: width,
  33566. height: height,
  33567. subdivisions: subdivisions,
  33568. updatable: updatable
  33569. };
  33570. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33571. };
  33572. /**
  33573. * Creates a tiled ground mesh.
  33574. * Please consider using the same method from the MeshBuilder class instead.
  33575. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33576. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33577. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33578. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33579. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33580. * numbers of subdivisions on the ground width and height of each tile.
  33581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33582. */
  33583. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33584. var options = {
  33585. xmin: xmin,
  33586. zmin: zmin,
  33587. xmax: xmax,
  33588. zmax: zmax,
  33589. subdivisions: subdivisions,
  33590. precision: precision,
  33591. updatable: updatable
  33592. };
  33593. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33594. };
  33595. /**
  33596. * Creates a ground mesh from a height map.
  33597. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33598. * Please consider using the same method from the MeshBuilder class instead.
  33599. * The parameter `url` sets the URL of the height map image resource.
  33600. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33601. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33602. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33603. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33604. * 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).
  33605. * This function is passed the newly built mesh :
  33606. * ```javascript
  33607. * function(mesh) { // do things
  33608. * return; }
  33609. * ```
  33610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33611. */
  33612. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33613. var options = {
  33614. width: width,
  33615. height: height,
  33616. subdivisions: subdivisions,
  33617. minHeight: minHeight,
  33618. maxHeight: maxHeight,
  33619. updatable: updatable,
  33620. onReady: onReady
  33621. };
  33622. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33623. };
  33624. /**
  33625. * Creates a tube mesh.
  33626. * 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.
  33627. * Please consider using the same method from the MeshBuilder class instead.
  33628. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33629. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33630. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33631. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33632. * 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.
  33633. * It must return a radius value (positive float) :
  33634. * ```javascript
  33635. * var radiusFunction = function(i, distance) {
  33636. * // do things
  33637. * return radius; }
  33638. * ```
  33639. * 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
  33640. * 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
  33641. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33642. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33644. */
  33645. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33646. var options = {
  33647. path: path,
  33648. radius: radius,
  33649. tessellation: tessellation,
  33650. radiusFunction: radiusFunction,
  33651. arc: 1,
  33652. cap: cap,
  33653. updatable: updatable,
  33654. sideOrientation: sideOrientation,
  33655. instance: instance
  33656. };
  33657. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33658. };
  33659. /**
  33660. * Creates a polyhedron mesh.
  33661. * Please consider using the same method from the MeshBuilder class instead.
  33662. * 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
  33663. * to choose the wanted type.
  33664. * The parameter `size` (positive float, default 1) sets the polygon size.
  33665. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33666. * 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`.
  33667. * 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
  33668. * 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)`).
  33669. * 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
  33670. * 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.
  33671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33672. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33674. */
  33675. Mesh.CreatePolyhedron = function (name, options, scene) {
  33676. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33677. };
  33678. /**
  33679. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33680. * Please consider using the same method from the MeshBuilder class instead.
  33681. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33682. * 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`).
  33683. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33684. * 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.
  33685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33686. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33688. */
  33689. Mesh.CreateIcoSphere = function (name, options, scene) {
  33690. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33691. };
  33692. /**
  33693. * Creates a decal mesh.
  33694. * Please consider using the same method from the MeshBuilder class instead.
  33695. * 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.
  33696. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33697. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33698. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33699. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33700. */
  33701. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33702. var options = {
  33703. position: position,
  33704. normal: normal,
  33705. size: size,
  33706. angle: angle
  33707. };
  33708. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33709. };
  33710. // Skeletons
  33711. /**
  33712. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33713. */
  33714. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33715. if (!this._sourcePositions) {
  33716. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33717. if (!source) {
  33718. return this._sourcePositions;
  33719. }
  33720. this._sourcePositions = new Float32Array(source);
  33721. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33722. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33723. }
  33724. }
  33725. return this._sourcePositions;
  33726. };
  33727. /**
  33728. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33729. */
  33730. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33731. if (!this._sourceNormals) {
  33732. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33733. if (!source) {
  33734. return this._sourceNormals;
  33735. }
  33736. this._sourceNormals = new Float32Array(source);
  33737. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33738. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33739. }
  33740. }
  33741. return this._sourceNormals;
  33742. };
  33743. /**
  33744. * Updates the vertex buffer by applying transformation from the bones.
  33745. * Returns the Mesh.
  33746. *
  33747. * @param {skeleton} skeleton to apply
  33748. */
  33749. Mesh.prototype.applySkeleton = function (skeleton) {
  33750. if (!this.geometry) {
  33751. return this;
  33752. }
  33753. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33754. return this;
  33755. }
  33756. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33758. return this;
  33759. }
  33760. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33761. return this;
  33762. }
  33763. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33764. return this;
  33765. }
  33766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33767. return this;
  33768. }
  33769. if (!this._sourcePositions) {
  33770. var submeshes = this.subMeshes.slice();
  33771. this.setPositionsForCPUSkinning();
  33772. this.subMeshes = submeshes;
  33773. }
  33774. if (!this._sourceNormals) {
  33775. this.setNormalsForCPUSkinning();
  33776. }
  33777. // positionsData checks for not being Float32Array will only pass at most once
  33778. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33779. if (!positionsData) {
  33780. return this;
  33781. }
  33782. if (!(positionsData instanceof Float32Array)) {
  33783. positionsData = new Float32Array(positionsData);
  33784. }
  33785. // normalsData checks for not being Float32Array will only pass at most once
  33786. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33787. if (!normalsData) {
  33788. return this;
  33789. }
  33790. if (!(normalsData instanceof Float32Array)) {
  33791. normalsData = new Float32Array(normalsData);
  33792. }
  33793. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33794. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33795. if (!matricesWeightsData || !matricesIndicesData) {
  33796. return this;
  33797. }
  33798. var needExtras = this.numBoneInfluencers > 4;
  33799. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33800. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33801. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33802. var tempVector3 = BABYLON.Vector3.Zero();
  33803. var finalMatrix = new BABYLON.Matrix();
  33804. var tempMatrix = new BABYLON.Matrix();
  33805. var matWeightIdx = 0;
  33806. var inf;
  33807. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33808. var weight;
  33809. for (inf = 0; inf < 4; inf++) {
  33810. weight = matricesWeightsData[matWeightIdx + inf];
  33811. if (weight > 0) {
  33812. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33813. finalMatrix.addToSelf(tempMatrix);
  33814. }
  33815. }
  33816. if (needExtras) {
  33817. for (inf = 0; inf < 4; inf++) {
  33818. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33819. if (weight > 0) {
  33820. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33821. finalMatrix.addToSelf(tempMatrix);
  33822. }
  33823. }
  33824. }
  33825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33826. tempVector3.toArray(positionsData, index);
  33827. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33828. tempVector3.toArray(normalsData, index);
  33829. finalMatrix.reset();
  33830. }
  33831. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33832. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33833. return this;
  33834. };
  33835. // Tools
  33836. /**
  33837. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33838. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33839. */
  33840. Mesh.MinMax = function (meshes) {
  33841. var minVector = null;
  33842. var maxVector = null;
  33843. meshes.forEach(function (mesh, index, array) {
  33844. var boundingInfo = mesh.getBoundingInfo();
  33845. var boundingBox = boundingInfo.boundingBox;
  33846. if (!minVector || !maxVector) {
  33847. minVector = boundingBox.minimumWorld;
  33848. maxVector = boundingBox.maximumWorld;
  33849. }
  33850. else {
  33851. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33852. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33853. }
  33854. });
  33855. if (!minVector || !maxVector) {
  33856. return {
  33857. min: BABYLON.Vector3.Zero(),
  33858. max: BABYLON.Vector3.Zero()
  33859. };
  33860. }
  33861. return {
  33862. min: minVector,
  33863. max: maxVector
  33864. };
  33865. };
  33866. /**
  33867. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33868. */
  33869. Mesh.Center = function (meshesOrMinMaxVector) {
  33870. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33871. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33872. };
  33873. /**
  33874. * Merge the array of meshes into a single mesh for performance reasons.
  33875. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33876. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33877. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33878. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33879. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33880. */
  33881. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33882. if (disposeSource === void 0) { disposeSource = true; }
  33883. var index;
  33884. if (!allow32BitsIndices) {
  33885. var totalVertices = 0;
  33886. // Counting vertices
  33887. for (index = 0; index < meshes.length; index++) {
  33888. if (meshes[index]) {
  33889. totalVertices += meshes[index].getTotalVertices();
  33890. if (totalVertices > 65536) {
  33891. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33892. return null;
  33893. }
  33894. }
  33895. }
  33896. }
  33897. // Merge
  33898. var vertexData = null;
  33899. var otherVertexData;
  33900. var indiceArray = new Array();
  33901. var source = null;
  33902. for (index = 0; index < meshes.length; index++) {
  33903. if (meshes[index]) {
  33904. meshes[index].computeWorldMatrix(true);
  33905. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33906. otherVertexData.transform(meshes[index].getWorldMatrix());
  33907. if (vertexData) {
  33908. vertexData.merge(otherVertexData);
  33909. }
  33910. else {
  33911. vertexData = otherVertexData;
  33912. source = meshes[index];
  33913. }
  33914. if (subdivideWithSubMeshes) {
  33915. indiceArray.push(meshes[index].getTotalIndices());
  33916. }
  33917. }
  33918. }
  33919. source = source;
  33920. if (!meshSubclass) {
  33921. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33922. }
  33923. vertexData.applyToMesh(meshSubclass);
  33924. // Setting properties
  33925. meshSubclass.material = source.material;
  33926. meshSubclass.checkCollisions = source.checkCollisions;
  33927. // Cleaning
  33928. if (disposeSource) {
  33929. for (index = 0; index < meshes.length; index++) {
  33930. if (meshes[index]) {
  33931. meshes[index].dispose();
  33932. }
  33933. }
  33934. }
  33935. // Subdivide
  33936. if (subdivideWithSubMeshes) {
  33937. //-- removal of global submesh
  33938. meshSubclass.releaseSubMeshes();
  33939. index = 0;
  33940. var offset = 0;
  33941. //-- apply subdivision according to index table
  33942. while (index < indiceArray.length) {
  33943. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33944. offset += indiceArray[index];
  33945. index++;
  33946. }
  33947. }
  33948. return meshSubclass;
  33949. };
  33950. // Consts
  33951. Mesh._FRONTSIDE = 0;
  33952. Mesh._BACKSIDE = 1;
  33953. Mesh._DOUBLESIDE = 2;
  33954. Mesh._DEFAULTSIDE = 0;
  33955. Mesh._NO_CAP = 0;
  33956. Mesh._CAP_START = 1;
  33957. Mesh._CAP_END = 2;
  33958. Mesh._CAP_ALL = 3;
  33959. return Mesh;
  33960. }(BABYLON.AbstractMesh));
  33961. BABYLON.Mesh = Mesh;
  33962. })(BABYLON || (BABYLON = {}));
  33963. //# sourceMappingURL=babylon.mesh.js.map
  33964. var BABYLON;
  33965. (function (BABYLON) {
  33966. var BaseSubMesh = /** @class */ (function () {
  33967. function BaseSubMesh() {
  33968. }
  33969. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33970. get: function () {
  33971. return this._materialEffect;
  33972. },
  33973. enumerable: true,
  33974. configurable: true
  33975. });
  33976. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33977. if (defines === void 0) { defines = null; }
  33978. if (this._materialEffect === effect) {
  33979. if (!effect) {
  33980. this._materialDefines = null;
  33981. }
  33982. return;
  33983. }
  33984. this._materialDefines = defines;
  33985. this._materialEffect = effect;
  33986. };
  33987. return BaseSubMesh;
  33988. }());
  33989. BABYLON.BaseSubMesh = BaseSubMesh;
  33990. var SubMesh = /** @class */ (function (_super) {
  33991. __extends(SubMesh, _super);
  33992. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33993. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33994. var _this = _super.call(this) || this;
  33995. _this.materialIndex = materialIndex;
  33996. _this.verticesStart = verticesStart;
  33997. _this.verticesCount = verticesCount;
  33998. _this.indexStart = indexStart;
  33999. _this.indexCount = indexCount;
  34000. _this._renderId = 0;
  34001. _this._mesh = mesh;
  34002. _this._renderingMesh = renderingMesh || mesh;
  34003. mesh.subMeshes.push(_this);
  34004. _this._trianglePlanes = [];
  34005. _this._id = mesh.subMeshes.length - 1;
  34006. if (createBoundingBox) {
  34007. _this.refreshBoundingInfo();
  34008. mesh.computeWorldMatrix(true);
  34009. }
  34010. return _this;
  34011. }
  34012. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34013. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34014. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34015. };
  34016. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34017. get: function () {
  34018. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34019. },
  34020. enumerable: true,
  34021. configurable: true
  34022. });
  34023. /**
  34024. * Returns the submesh BoudingInfo object.
  34025. */
  34026. SubMesh.prototype.getBoundingInfo = function () {
  34027. if (this.IsGlobal) {
  34028. return this._mesh.getBoundingInfo();
  34029. }
  34030. return this._boundingInfo;
  34031. };
  34032. /**
  34033. * Sets the submesh BoundingInfo.
  34034. * Return the SubMesh.
  34035. */
  34036. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34037. this._boundingInfo = boundingInfo;
  34038. return this;
  34039. };
  34040. /**
  34041. * Returns the mesh of the current submesh.
  34042. */
  34043. SubMesh.prototype.getMesh = function () {
  34044. return this._mesh;
  34045. };
  34046. /**
  34047. * Returns the rendering mesh of the submesh.
  34048. */
  34049. SubMesh.prototype.getRenderingMesh = function () {
  34050. return this._renderingMesh;
  34051. };
  34052. /**
  34053. * Returns the submesh material.
  34054. */
  34055. SubMesh.prototype.getMaterial = function () {
  34056. var rootMaterial = this._renderingMesh.material;
  34057. if (rootMaterial === null || rootMaterial === undefined) {
  34058. return this._mesh.getScene().defaultMaterial;
  34059. }
  34060. else if (rootMaterial.getSubMaterial) {
  34061. var multiMaterial = rootMaterial;
  34062. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34063. if (this._currentMaterial !== effectiveMaterial) {
  34064. this._currentMaterial = effectiveMaterial;
  34065. this._materialDefines = null;
  34066. }
  34067. return effectiveMaterial;
  34068. }
  34069. return rootMaterial;
  34070. };
  34071. // Methods
  34072. /**
  34073. * Sets a new updated BoundingInfo object to the submesh.
  34074. * Returns the SubMesh.
  34075. */
  34076. SubMesh.prototype.refreshBoundingInfo = function () {
  34077. this._lastColliderWorldVertices = null;
  34078. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34079. return this;
  34080. }
  34081. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34082. if (!data) {
  34083. this._boundingInfo = this._mesh.getBoundingInfo();
  34084. return this;
  34085. }
  34086. var indices = this._renderingMesh.getIndices();
  34087. var extend;
  34088. //is this the only submesh?
  34089. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34090. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34091. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34092. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34093. }
  34094. else {
  34095. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34096. }
  34097. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34098. return this;
  34099. };
  34100. SubMesh.prototype._checkCollision = function (collider) {
  34101. var boundingInfo = this.getBoundingInfo();
  34102. return boundingInfo._checkCollision(collider);
  34103. };
  34104. /**
  34105. * Updates the submesh BoundingInfo.
  34106. * Returns the Submesh.
  34107. */
  34108. SubMesh.prototype.updateBoundingInfo = function (world) {
  34109. var boundingInfo = this.getBoundingInfo();
  34110. if (!boundingInfo) {
  34111. this.refreshBoundingInfo();
  34112. boundingInfo = this.getBoundingInfo();
  34113. }
  34114. boundingInfo.update(world);
  34115. return this;
  34116. };
  34117. /**
  34118. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34119. * Boolean returned.
  34120. */
  34121. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34122. var boundingInfo = this.getBoundingInfo();
  34123. if (!boundingInfo) {
  34124. return false;
  34125. }
  34126. return boundingInfo.isInFrustum(frustumPlanes);
  34127. };
  34128. /**
  34129. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34130. * Boolean returned.
  34131. */
  34132. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34133. var boundingInfo = this.getBoundingInfo();
  34134. if (!boundingInfo) {
  34135. return false;
  34136. }
  34137. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34138. };
  34139. /**
  34140. * Renders the submesh.
  34141. * Returns it.
  34142. */
  34143. SubMesh.prototype.render = function (enableAlphaMode) {
  34144. this._renderingMesh.render(this, enableAlphaMode);
  34145. return this;
  34146. };
  34147. /**
  34148. * Returns a new Index Buffer.
  34149. * Type returned : WebGLBuffer.
  34150. */
  34151. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34152. if (!this._linesIndexBuffer) {
  34153. var linesIndices = [];
  34154. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34155. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34156. }
  34157. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34158. this.linesIndexCount = linesIndices.length;
  34159. }
  34160. return this._linesIndexBuffer;
  34161. };
  34162. /**
  34163. * True is the passed Ray intersects the submesh bounding box.
  34164. * Boolean returned.
  34165. */
  34166. SubMesh.prototype.canIntersects = function (ray) {
  34167. var boundingInfo = this.getBoundingInfo();
  34168. if (!boundingInfo) {
  34169. return false;
  34170. }
  34171. return ray.intersectsBox(boundingInfo.boundingBox);
  34172. };
  34173. /**
  34174. * Returns an object IntersectionInfo.
  34175. */
  34176. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34177. var intersectInfo = null;
  34178. var material = this.getMaterial();
  34179. if (!material) {
  34180. return null;
  34181. }
  34182. switch (material.fillMode) {
  34183. case BABYLON.Material.PointListDrawMode:
  34184. case BABYLON.Material.LineListDrawMode:
  34185. case BABYLON.Material.LineLoopDrawMode:
  34186. case BABYLON.Material.LineStripDrawMode:
  34187. case BABYLON.Material.TriangleFanDrawMode:
  34188. case BABYLON.Material.TriangleStripDrawMode:
  34189. return null;
  34190. }
  34191. // LineMesh first as it's also a Mesh...
  34192. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34193. var lineMesh = this._mesh;
  34194. // Line test
  34195. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34196. var p0 = positions[indices[index]];
  34197. var p1 = positions[indices[index + 1]];
  34198. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34199. if (length < 0) {
  34200. continue;
  34201. }
  34202. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34203. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34204. if (fastCheck) {
  34205. break;
  34206. }
  34207. }
  34208. }
  34209. }
  34210. else {
  34211. // Triangles test
  34212. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34213. var p0 = positions[indices[index]];
  34214. var p1 = positions[indices[index + 1]];
  34215. var p2 = positions[indices[index + 2]];
  34216. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34217. if (currentIntersectInfo) {
  34218. if (currentIntersectInfo.distance < 0) {
  34219. continue;
  34220. }
  34221. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34222. intersectInfo = currentIntersectInfo;
  34223. intersectInfo.faceId = index / 3;
  34224. if (fastCheck) {
  34225. break;
  34226. }
  34227. }
  34228. }
  34229. }
  34230. }
  34231. return intersectInfo;
  34232. };
  34233. SubMesh.prototype._rebuild = function () {
  34234. if (this._linesIndexBuffer) {
  34235. this._linesIndexBuffer = null;
  34236. }
  34237. };
  34238. // Clone
  34239. /**
  34240. * Creates a new Submesh from the passed Mesh.
  34241. */
  34242. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34243. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34244. if (!this.IsGlobal) {
  34245. var boundingInfo = this.getBoundingInfo();
  34246. if (!boundingInfo) {
  34247. return result;
  34248. }
  34249. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34250. }
  34251. return result;
  34252. };
  34253. // Dispose
  34254. /**
  34255. * Disposes the Submesh.
  34256. * Returns nothing.
  34257. */
  34258. SubMesh.prototype.dispose = function () {
  34259. if (this._linesIndexBuffer) {
  34260. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34261. this._linesIndexBuffer = null;
  34262. }
  34263. // Remove from mesh
  34264. var index = this._mesh.subMeshes.indexOf(this);
  34265. this._mesh.subMeshes.splice(index, 1);
  34266. };
  34267. // Statics
  34268. /**
  34269. * Creates a new Submesh from the passed parameters :
  34270. * - materialIndex (integer) : the index of the main mesh material.
  34271. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34272. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34273. * - mesh (Mesh) : the main mesh to create the submesh from.
  34274. * - renderingMesh (optional Mesh) : rendering mesh.
  34275. */
  34276. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34277. var minVertexIndex = Number.MAX_VALUE;
  34278. var maxVertexIndex = -Number.MAX_VALUE;
  34279. renderingMesh = (renderingMesh || mesh);
  34280. var indices = renderingMesh.getIndices();
  34281. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34282. var vertexIndex = indices[index];
  34283. if (vertexIndex < minVertexIndex)
  34284. minVertexIndex = vertexIndex;
  34285. if (vertexIndex > maxVertexIndex)
  34286. maxVertexIndex = vertexIndex;
  34287. }
  34288. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34289. };
  34290. return SubMesh;
  34291. }(BaseSubMesh));
  34292. BABYLON.SubMesh = SubMesh;
  34293. })(BABYLON || (BABYLON = {}));
  34294. //# sourceMappingURL=babylon.subMesh.js.map
  34295. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34296. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34297. s = arguments[i];
  34298. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34299. t[p] = s[p];
  34300. }
  34301. return t;
  34302. };
  34303. var BABYLON;
  34304. (function (BABYLON) {
  34305. /**
  34306. * Manages the defines for the Material
  34307. */
  34308. var MaterialDefines = /** @class */ (function () {
  34309. function MaterialDefines() {
  34310. this._isDirty = true;
  34311. /** @hidden */
  34312. this._areLightsDirty = true;
  34313. /** @hidden */
  34314. this._areAttributesDirty = true;
  34315. /** @hidden */
  34316. this._areTexturesDirty = true;
  34317. /** @hidden */
  34318. this._areFresnelDirty = true;
  34319. /** @hidden */
  34320. this._areMiscDirty = true;
  34321. /** @hidden */
  34322. this._areImageProcessingDirty = true;
  34323. /** @hidden */
  34324. this._normals = false;
  34325. /** @hidden */
  34326. this._uvs = false;
  34327. /** @hidden */
  34328. this._needNormals = false;
  34329. /** @hidden */
  34330. this._needUVs = false;
  34331. }
  34332. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34333. /**
  34334. * Specifies if the material needs to be re-calculated
  34335. */
  34336. get: function () {
  34337. return this._isDirty;
  34338. },
  34339. enumerable: true,
  34340. configurable: true
  34341. });
  34342. /**
  34343. * Marks the material to indicate that it has been re-calculated
  34344. */
  34345. MaterialDefines.prototype.markAsProcessed = function () {
  34346. this._isDirty = false;
  34347. this._areAttributesDirty = false;
  34348. this._areTexturesDirty = false;
  34349. this._areFresnelDirty = false;
  34350. this._areLightsDirty = false;
  34351. this._areMiscDirty = false;
  34352. this._areImageProcessingDirty = false;
  34353. };
  34354. /**
  34355. * Marks the material to indicate that it needs to be re-calculated
  34356. */
  34357. MaterialDefines.prototype.markAsUnprocessed = function () {
  34358. this._isDirty = true;
  34359. };
  34360. /**
  34361. * Marks the material to indicate all of its defines need to be re-calculated
  34362. */
  34363. MaterialDefines.prototype.markAllAsDirty = function () {
  34364. this._areTexturesDirty = true;
  34365. this._areAttributesDirty = true;
  34366. this._areLightsDirty = true;
  34367. this._areFresnelDirty = true;
  34368. this._areMiscDirty = true;
  34369. this._areImageProcessingDirty = true;
  34370. this._isDirty = true;
  34371. };
  34372. /**
  34373. * Marks the material to indicate that image processing needs to be re-calculated
  34374. */
  34375. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34376. this._areImageProcessingDirty = true;
  34377. this._isDirty = true;
  34378. };
  34379. /**
  34380. * Marks the material to indicate the lights need to be re-calculated
  34381. */
  34382. MaterialDefines.prototype.markAsLightDirty = function () {
  34383. this._areLightsDirty = true;
  34384. this._isDirty = true;
  34385. };
  34386. /**
  34387. * Marks the attribute state as changed
  34388. */
  34389. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34390. this._areAttributesDirty = true;
  34391. this._isDirty = true;
  34392. };
  34393. /**
  34394. * Marks the texture state as changed
  34395. */
  34396. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34397. this._areTexturesDirty = true;
  34398. this._isDirty = true;
  34399. };
  34400. /**
  34401. * Marks the fresnel state as changed
  34402. */
  34403. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34404. this._areFresnelDirty = true;
  34405. this._isDirty = true;
  34406. };
  34407. /**
  34408. * Marks the misc state as changed
  34409. */
  34410. MaterialDefines.prototype.markAsMiscDirty = function () {
  34411. this._areMiscDirty = true;
  34412. this._isDirty = true;
  34413. };
  34414. /**
  34415. * Rebuilds the material defines
  34416. */
  34417. MaterialDefines.prototype.rebuild = function () {
  34418. if (this._keys) {
  34419. delete this._keys;
  34420. }
  34421. this._keys = [];
  34422. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34423. var key = _a[_i];
  34424. if (key[0] === "_") {
  34425. continue;
  34426. }
  34427. this._keys.push(key);
  34428. }
  34429. };
  34430. /**
  34431. * Specifies if two material defines are equal
  34432. * @param other - A material define instance to compare to
  34433. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34434. */
  34435. MaterialDefines.prototype.isEqual = function (other) {
  34436. if (this._keys.length !== other._keys.length) {
  34437. return false;
  34438. }
  34439. for (var index = 0; index < this._keys.length; index++) {
  34440. var prop = this._keys[index];
  34441. if (this[prop] !== other[prop]) {
  34442. return false;
  34443. }
  34444. }
  34445. return true;
  34446. };
  34447. /**
  34448. * Clones this instance's defines to another instance
  34449. * @param other - material defines to clone values to
  34450. */
  34451. MaterialDefines.prototype.cloneTo = function (other) {
  34452. if (this._keys.length !== other._keys.length) {
  34453. other._keys = this._keys.slice(0);
  34454. }
  34455. for (var index = 0; index < this._keys.length; index++) {
  34456. var prop = this._keys[index];
  34457. other[prop] = this[prop];
  34458. }
  34459. };
  34460. /**
  34461. * Resets the material define values
  34462. */
  34463. MaterialDefines.prototype.reset = function () {
  34464. for (var index = 0; index < this._keys.length; index++) {
  34465. var prop = this._keys[index];
  34466. var type = typeof this[prop];
  34467. switch (type) {
  34468. case "number":
  34469. this[prop] = 0;
  34470. break;
  34471. case "string":
  34472. this[prop] = "";
  34473. break;
  34474. default:
  34475. this[prop] = false;
  34476. break;
  34477. }
  34478. }
  34479. };
  34480. /**
  34481. * Converts the material define values to a string
  34482. * @returns - String of material define information
  34483. */
  34484. MaterialDefines.prototype.toString = function () {
  34485. var result = "";
  34486. for (var index = 0; index < this._keys.length; index++) {
  34487. var prop = this._keys[index];
  34488. var value = this[prop];
  34489. var type = typeof value;
  34490. switch (type) {
  34491. case "number":
  34492. case "string":
  34493. result += "#define " + prop + " " + value + "\n";
  34494. break;
  34495. default:
  34496. if (value) {
  34497. result += "#define " + prop + "\n";
  34498. }
  34499. break;
  34500. }
  34501. }
  34502. return result;
  34503. };
  34504. return MaterialDefines;
  34505. }());
  34506. BABYLON.MaterialDefines = MaterialDefines;
  34507. /**
  34508. * Base class for the main features of a material in Babylon.js
  34509. */
  34510. var Material = /** @class */ (function () {
  34511. /**
  34512. * Creates a material instance
  34513. * @param name defines the name of the material
  34514. * @param scene defines the scene to reference
  34515. * @param doNotAdd specifies if the material should be added to the scene
  34516. */
  34517. function Material(name, scene, doNotAdd) {
  34518. /**
  34519. * Specifies if the ready state should be checked on each call
  34520. */
  34521. this.checkReadyOnEveryCall = false;
  34522. /**
  34523. * Specifies if the ready state should be checked once
  34524. */
  34525. this.checkReadyOnlyOnce = false;
  34526. /**
  34527. * The state of the material
  34528. */
  34529. this.state = "";
  34530. /**
  34531. * The alpha value of the material
  34532. */
  34533. this._alpha = 1.0;
  34534. /**
  34535. * Specifies if back face culling is enabled
  34536. */
  34537. this._backFaceCulling = true;
  34538. /**
  34539. * Specifies if the material should be serialized
  34540. */
  34541. this.doNotSerialize = false;
  34542. /**
  34543. * Specifies if the effect should be stored on sub meshes
  34544. */
  34545. this.storeEffectOnSubMeshes = false;
  34546. /**
  34547. * An event triggered when the material is disposed
  34548. */
  34549. this.onDisposeObservable = new BABYLON.Observable();
  34550. /**
  34551. * An event triggered when the material is bound
  34552. */
  34553. this.onBindObservable = new BABYLON.Observable();
  34554. /**
  34555. * An event triggered when the material is unbound
  34556. */
  34557. this.onUnBindObservable = new BABYLON.Observable();
  34558. /**
  34559. * Stores the value of the alpha mode
  34560. */
  34561. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34562. /**
  34563. * Stores the state of the need depth pre-pass value
  34564. */
  34565. this._needDepthPrePass = false;
  34566. /**
  34567. * Specifies if depth writing should be disabled
  34568. */
  34569. this.disableDepthWrite = false;
  34570. /**
  34571. * Specifies if depth writing should be forced
  34572. */
  34573. this.forceDepthWrite = false;
  34574. /**
  34575. * Specifies if there should be a separate pass for culling
  34576. */
  34577. this.separateCullingPass = false;
  34578. /**
  34579. * Stores the state specifing if fog should be enabled
  34580. */
  34581. this._fogEnabled = true;
  34582. /**
  34583. * Stores the size of points
  34584. */
  34585. this.pointSize = 1.0;
  34586. /**
  34587. * Stores the z offset value
  34588. */
  34589. this.zOffset = 0;
  34590. /**
  34591. * Specifies if the material was previously ready
  34592. */
  34593. this._wasPreviouslyReady = false;
  34594. /**
  34595. * Stores the fill mode state
  34596. */
  34597. this._fillMode = Material.TriangleFillMode;
  34598. this.name = name;
  34599. this.id = name || BABYLON.Tools.RandomId();
  34600. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34601. this.uniqueId = this._scene.getUniqueId();
  34602. if (this._scene.useRightHandedSystem) {
  34603. this.sideOrientation = Material.ClockWiseSideOrientation;
  34604. }
  34605. else {
  34606. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34607. }
  34608. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34609. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34610. if (!doNotAdd) {
  34611. this._scene.materials.push(this);
  34612. }
  34613. }
  34614. Object.defineProperty(Material, "TriangleFillMode", {
  34615. /**
  34616. * Returns the triangle fill mode
  34617. */
  34618. get: function () {
  34619. return Material._TriangleFillMode;
  34620. },
  34621. enumerable: true,
  34622. configurable: true
  34623. });
  34624. Object.defineProperty(Material, "WireFrameFillMode", {
  34625. /**
  34626. * Returns the wireframe mode
  34627. */
  34628. get: function () {
  34629. return Material._WireFrameFillMode;
  34630. },
  34631. enumerable: true,
  34632. configurable: true
  34633. });
  34634. Object.defineProperty(Material, "PointFillMode", {
  34635. /**
  34636. * Returns the point fill mode
  34637. */
  34638. get: function () {
  34639. return Material._PointFillMode;
  34640. },
  34641. enumerable: true,
  34642. configurable: true
  34643. });
  34644. Object.defineProperty(Material, "PointListDrawMode", {
  34645. /**
  34646. * Returns the point list draw mode
  34647. */
  34648. get: function () {
  34649. return Material._PointListDrawMode;
  34650. },
  34651. enumerable: true,
  34652. configurable: true
  34653. });
  34654. Object.defineProperty(Material, "LineListDrawMode", {
  34655. /**
  34656. * Returns the line list draw mode
  34657. */
  34658. get: function () {
  34659. return Material._LineListDrawMode;
  34660. },
  34661. enumerable: true,
  34662. configurable: true
  34663. });
  34664. Object.defineProperty(Material, "LineLoopDrawMode", {
  34665. /**
  34666. * Returns the line loop draw mode
  34667. */
  34668. get: function () {
  34669. return Material._LineLoopDrawMode;
  34670. },
  34671. enumerable: true,
  34672. configurable: true
  34673. });
  34674. Object.defineProperty(Material, "LineStripDrawMode", {
  34675. /**
  34676. * Returns the line strip draw mode
  34677. */
  34678. get: function () {
  34679. return Material._LineStripDrawMode;
  34680. },
  34681. enumerable: true,
  34682. configurable: true
  34683. });
  34684. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34685. /**
  34686. * Returns the triangle strip draw mode
  34687. */
  34688. get: function () {
  34689. return Material._TriangleStripDrawMode;
  34690. },
  34691. enumerable: true,
  34692. configurable: true
  34693. });
  34694. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34695. /**
  34696. * Returns the triangle fan draw mode
  34697. */
  34698. get: function () {
  34699. return Material._TriangleFanDrawMode;
  34700. },
  34701. enumerable: true,
  34702. configurable: true
  34703. });
  34704. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34705. /**
  34706. * Returns the clock-wise side orientation
  34707. */
  34708. get: function () {
  34709. return Material._ClockWiseSideOrientation;
  34710. },
  34711. enumerable: true,
  34712. configurable: true
  34713. });
  34714. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34715. /**
  34716. * Returns the counter clock-wise side orientation
  34717. */
  34718. get: function () {
  34719. return Material._CounterClockWiseSideOrientation;
  34720. },
  34721. enumerable: true,
  34722. configurable: true
  34723. });
  34724. Object.defineProperty(Material, "TextureDirtyFlag", {
  34725. /**
  34726. * Returns the dirty texture flag value
  34727. */
  34728. get: function () {
  34729. return Material._TextureDirtyFlag;
  34730. },
  34731. enumerable: true,
  34732. configurable: true
  34733. });
  34734. Object.defineProperty(Material, "LightDirtyFlag", {
  34735. /**
  34736. * Returns the dirty light flag value
  34737. */
  34738. get: function () {
  34739. return Material._LightDirtyFlag;
  34740. },
  34741. enumerable: true,
  34742. configurable: true
  34743. });
  34744. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34745. /**
  34746. * Returns the dirty fresnel flag value
  34747. */
  34748. get: function () {
  34749. return Material._FresnelDirtyFlag;
  34750. },
  34751. enumerable: true,
  34752. configurable: true
  34753. });
  34754. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34755. /**
  34756. * Returns the dirty attributes flag value
  34757. */
  34758. get: function () {
  34759. return Material._AttributesDirtyFlag;
  34760. },
  34761. enumerable: true,
  34762. configurable: true
  34763. });
  34764. Object.defineProperty(Material, "MiscDirtyFlag", {
  34765. /**
  34766. * Returns the dirty misc flag value
  34767. */
  34768. get: function () {
  34769. return Material._MiscDirtyFlag;
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(Material.prototype, "alpha", {
  34775. /**
  34776. * Gets the alpha value of the material
  34777. */
  34778. get: function () {
  34779. return this._alpha;
  34780. },
  34781. /**
  34782. * Sets the alpha value of the material
  34783. */
  34784. set: function (value) {
  34785. if (this._alpha === value) {
  34786. return;
  34787. }
  34788. this._alpha = value;
  34789. this.markAsDirty(Material.MiscDirtyFlag);
  34790. },
  34791. enumerable: true,
  34792. configurable: true
  34793. });
  34794. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34795. /**
  34796. * Gets the back-face culling state
  34797. */
  34798. get: function () {
  34799. return this._backFaceCulling;
  34800. },
  34801. /**
  34802. * Sets the back-face culling state
  34803. */
  34804. set: function (value) {
  34805. if (this._backFaceCulling === value) {
  34806. return;
  34807. }
  34808. this._backFaceCulling = value;
  34809. this.markAsDirty(Material.TextureDirtyFlag);
  34810. },
  34811. enumerable: true,
  34812. configurable: true
  34813. });
  34814. Object.defineProperty(Material.prototype, "onDispose", {
  34815. /**
  34816. * Called during a dispose event
  34817. */
  34818. set: function (callback) {
  34819. if (this._onDisposeObserver) {
  34820. this.onDisposeObservable.remove(this._onDisposeObserver);
  34821. }
  34822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material.prototype, "onBind", {
  34828. /**
  34829. * Called during a bind event
  34830. */
  34831. set: function (callback) {
  34832. if (this._onBindObserver) {
  34833. this.onBindObservable.remove(this._onBindObserver);
  34834. }
  34835. this._onBindObserver = this.onBindObservable.add(callback);
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(Material.prototype, "alphaMode", {
  34841. /**
  34842. * Gets the value of the alpha mode
  34843. */
  34844. get: function () {
  34845. return this._alphaMode;
  34846. },
  34847. /**
  34848. * Sets the value of the alpha mode.
  34849. *
  34850. * | Value | Type | Description |
  34851. * | --- | --- | --- |
  34852. * | 0 | ALPHA_DISABLE | |
  34853. * | 1 | ALPHA_ADD | |
  34854. * | 2 | ALPHA_COMBINE | |
  34855. * | 3 | ALPHA_SUBTRACT | |
  34856. * | 4 | ALPHA_MULTIPLY | |
  34857. * | 5 | ALPHA_MAXIMIZED | |
  34858. * | 6 | ALPHA_ONEONE | |
  34859. * | 7 | ALPHA_PREMULTIPLIED | |
  34860. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34861. * | 9 | ALPHA_INTERPOLATE | |
  34862. * | 10 | ALPHA_SCREENMODE | |
  34863. *
  34864. */
  34865. set: function (value) {
  34866. if (this._alphaMode === value) {
  34867. return;
  34868. }
  34869. this._alphaMode = value;
  34870. this.markAsDirty(Material.TextureDirtyFlag);
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34876. /**
  34877. * Gets the depth pre-pass value
  34878. */
  34879. get: function () {
  34880. return this._needDepthPrePass;
  34881. },
  34882. /**
  34883. * Sets the need depth pre-pass value
  34884. */
  34885. set: function (value) {
  34886. if (this._needDepthPrePass === value) {
  34887. return;
  34888. }
  34889. this._needDepthPrePass = value;
  34890. if (this._needDepthPrePass) {
  34891. this.checkReadyOnEveryCall = true;
  34892. }
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(Material.prototype, "fogEnabled", {
  34898. /**
  34899. * Gets the value of the fog enabled state
  34900. */
  34901. get: function () {
  34902. return this._fogEnabled;
  34903. },
  34904. /**
  34905. * Sets the state for enabling fog
  34906. */
  34907. set: function (value) {
  34908. if (this._fogEnabled === value) {
  34909. return;
  34910. }
  34911. this._fogEnabled = value;
  34912. this.markAsDirty(Material.MiscDirtyFlag);
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material.prototype, "wireframe", {
  34918. /**
  34919. * Gets a value specifying if wireframe mode is enabled
  34920. */
  34921. get: function () {
  34922. switch (this._fillMode) {
  34923. case Material.WireFrameFillMode:
  34924. case Material.LineListDrawMode:
  34925. case Material.LineLoopDrawMode:
  34926. case Material.LineStripDrawMode:
  34927. return true;
  34928. }
  34929. return this._scene.forceWireframe;
  34930. },
  34931. /**
  34932. * Sets the state of wireframe mode
  34933. */
  34934. set: function (value) {
  34935. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34936. },
  34937. enumerable: true,
  34938. configurable: true
  34939. });
  34940. Object.defineProperty(Material.prototype, "pointsCloud", {
  34941. /**
  34942. * Gets the value specifying if point clouds are enabled
  34943. */
  34944. get: function () {
  34945. switch (this._fillMode) {
  34946. case Material.PointFillMode:
  34947. case Material.PointListDrawMode:
  34948. return true;
  34949. }
  34950. return this._scene.forcePointsCloud;
  34951. },
  34952. /**
  34953. * Sets the state of point cloud mode
  34954. */
  34955. set: function (value) {
  34956. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. Object.defineProperty(Material.prototype, "fillMode", {
  34962. /**
  34963. * Gets the material fill mode
  34964. */
  34965. get: function () {
  34966. return this._fillMode;
  34967. },
  34968. /**
  34969. * Sets the material fill mode
  34970. */
  34971. set: function (value) {
  34972. if (this._fillMode === value) {
  34973. return;
  34974. }
  34975. this._fillMode = value;
  34976. this.markAsDirty(Material.MiscDirtyFlag);
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. /**
  34982. * Returns a string representation of the current material
  34983. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34984. * @returns a string with material information
  34985. */
  34986. Material.prototype.toString = function (fullDetails) {
  34987. var ret = "Name: " + this.name;
  34988. if (fullDetails) {
  34989. }
  34990. return ret;
  34991. };
  34992. /**
  34993. * Gets the class name of the material
  34994. * @returns a string with the class name of the material
  34995. */
  34996. Material.prototype.getClassName = function () {
  34997. return "Material";
  34998. };
  34999. Object.defineProperty(Material.prototype, "isFrozen", {
  35000. /**
  35001. * Specifies if updates for the material been locked
  35002. */
  35003. get: function () {
  35004. return this.checkReadyOnlyOnce;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. /**
  35010. * Locks updates for the material
  35011. */
  35012. Material.prototype.freeze = function () {
  35013. this.checkReadyOnlyOnce = true;
  35014. };
  35015. /**
  35016. * Unlocks updates for the material
  35017. */
  35018. Material.prototype.unfreeze = function () {
  35019. this.checkReadyOnlyOnce = false;
  35020. };
  35021. /**
  35022. * Specifies if the material is ready to be used
  35023. * @param mesh defines the mesh to check
  35024. * @param useInstances specifies if instances should be used
  35025. * @returns a boolean indicating if the material is ready to be used
  35026. */
  35027. Material.prototype.isReady = function (mesh, useInstances) {
  35028. return true;
  35029. };
  35030. /**
  35031. * Specifies that the submesh is ready to be used
  35032. * @param mesh defines the mesh to check
  35033. * @param subMesh defines which submesh to check
  35034. * @param useInstances specifies that instances should be used
  35035. * @returns a boolean indicating that the submesh is ready or not
  35036. */
  35037. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35038. return false;
  35039. };
  35040. /**
  35041. * Returns the material effect
  35042. * @returns the effect associated with the material
  35043. */
  35044. Material.prototype.getEffect = function () {
  35045. return this._effect;
  35046. };
  35047. /**
  35048. * Returns the current scene
  35049. * @returns a Scene
  35050. */
  35051. Material.prototype.getScene = function () {
  35052. return this._scene;
  35053. };
  35054. /**
  35055. * Specifies if the material will require alpha blending
  35056. * @returns a boolean specifying if alpha blending is needed
  35057. */
  35058. Material.prototype.needAlphaBlending = function () {
  35059. return (this.alpha < 1.0);
  35060. };
  35061. /**
  35062. * Specifies if the mesh will require alpha blending
  35063. * @param mesh defines the mesh to check
  35064. * @returns a boolean specifying if alpha blending is needed for the mesh
  35065. */
  35066. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35067. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35068. };
  35069. /**
  35070. * Specifies if this material should be rendered in alpha test mode
  35071. * @returns a boolean specifying if an alpha test is needed.
  35072. */
  35073. Material.prototype.needAlphaTesting = function () {
  35074. return false;
  35075. };
  35076. /**
  35077. * Gets the texture used for the alpha test
  35078. * @returns the texture to use for alpha testing
  35079. */
  35080. Material.prototype.getAlphaTestTexture = function () {
  35081. return null;
  35082. };
  35083. /**
  35084. * Marks the material to indicate that it needs to be re-calculated
  35085. */
  35086. Material.prototype.markDirty = function () {
  35087. this._wasPreviouslyReady = false;
  35088. };
  35089. /** @hidden */
  35090. Material.prototype._preBind = function (effect, overrideOrientation) {
  35091. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35092. var engine = this._scene.getEngine();
  35093. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35094. var reverse = orientation === Material.ClockWiseSideOrientation;
  35095. engine.enableEffect(effect ? effect : this._effect);
  35096. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35097. return reverse;
  35098. };
  35099. /**
  35100. * Binds the material to the mesh
  35101. * @param world defines the world transformation matrix
  35102. * @param mesh defines the mesh to bind the material to
  35103. */
  35104. Material.prototype.bind = function (world, mesh) {
  35105. };
  35106. /**
  35107. * Binds the submesh to the material
  35108. * @param world defines the world transformation matrix
  35109. * @param mesh defines the mesh containing the submesh
  35110. * @param subMesh defines the submesh to bind the material to
  35111. */
  35112. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35113. };
  35114. /**
  35115. * Binds the world matrix to the material
  35116. * @param world defines the world transformation matrix
  35117. */
  35118. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35119. };
  35120. /**
  35121. * Binds the scene's uniform buffer to the effect.
  35122. * @param effect defines the effect to bind to the scene uniform buffer
  35123. * @param sceneUbo defines the uniform buffer storing scene data
  35124. */
  35125. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35126. sceneUbo.bindToEffect(effect, "Scene");
  35127. };
  35128. /**
  35129. * Binds the view matrix to the effect
  35130. * @param effect defines the effect to bind the view matrix to
  35131. */
  35132. Material.prototype.bindView = function (effect) {
  35133. if (!this._useUBO) {
  35134. effect.setMatrix("view", this.getScene().getViewMatrix());
  35135. }
  35136. else {
  35137. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35138. }
  35139. };
  35140. /**
  35141. * Binds the view projection matrix to the effect
  35142. * @param effect defines the effect to bind the view projection matrix to
  35143. */
  35144. Material.prototype.bindViewProjection = function (effect) {
  35145. if (!this._useUBO) {
  35146. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35147. }
  35148. else {
  35149. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35150. }
  35151. };
  35152. /**
  35153. * Specifies if material alpha testing should be turned on for the mesh
  35154. * @param mesh defines the mesh to check
  35155. */
  35156. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35157. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35158. };
  35159. /**
  35160. * Processes to execute after binding the material to a mesh
  35161. * @param mesh defines the rendered mesh
  35162. */
  35163. Material.prototype._afterBind = function (mesh) {
  35164. this._scene._cachedMaterial = this;
  35165. if (mesh) {
  35166. this._scene._cachedVisibility = mesh.visibility;
  35167. }
  35168. else {
  35169. this._scene._cachedVisibility = 1;
  35170. }
  35171. if (mesh) {
  35172. this.onBindObservable.notifyObservers(mesh);
  35173. }
  35174. if (this.disableDepthWrite) {
  35175. var engine = this._scene.getEngine();
  35176. this._cachedDepthWriteState = engine.getDepthWrite();
  35177. engine.setDepthWrite(false);
  35178. }
  35179. };
  35180. /**
  35181. * Unbinds the material from the mesh
  35182. */
  35183. Material.prototype.unbind = function () {
  35184. this.onUnBindObservable.notifyObservers(this);
  35185. if (this.disableDepthWrite) {
  35186. var engine = this._scene.getEngine();
  35187. engine.setDepthWrite(this._cachedDepthWriteState);
  35188. }
  35189. };
  35190. /**
  35191. * Gets the active textures from the material
  35192. * @returns an array of textures
  35193. */
  35194. Material.prototype.getActiveTextures = function () {
  35195. return [];
  35196. };
  35197. /**
  35198. * Specifies if the material uses a texture
  35199. * @param texture defines the texture to check against the material
  35200. * @returns a boolean specifying if the material uses the texture
  35201. */
  35202. Material.prototype.hasTexture = function (texture) {
  35203. return false;
  35204. };
  35205. /**
  35206. * Makes a duplicate of the material, and gives it a new name
  35207. * @param name defines the new name for the duplicated material
  35208. * @returns the cloned material
  35209. */
  35210. Material.prototype.clone = function (name) {
  35211. return null;
  35212. };
  35213. /**
  35214. * Gets the meshes bound to the material
  35215. * @returns an array of meshes bound to the material
  35216. */
  35217. Material.prototype.getBindedMeshes = function () {
  35218. var result = new Array();
  35219. for (var index = 0; index < this._scene.meshes.length; index++) {
  35220. var mesh = this._scene.meshes[index];
  35221. if (mesh.material === this) {
  35222. result.push(mesh);
  35223. }
  35224. }
  35225. return result;
  35226. };
  35227. /**
  35228. * Force shader compilation
  35229. * @param mesh defines the mesh associated with this material
  35230. * @param onCompiled defines a function to execute once the material is compiled
  35231. * @param options defines the options to configure the compilation
  35232. */
  35233. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35234. var _this = this;
  35235. var localOptions = __assign({ clipPlane: false }, options);
  35236. var subMesh = new BABYLON.BaseSubMesh();
  35237. var scene = this.getScene();
  35238. var checkReady = function () {
  35239. if (!_this._scene || !_this._scene.getEngine()) {
  35240. return;
  35241. }
  35242. if (subMesh._materialDefines) {
  35243. subMesh._materialDefines._renderId = -1;
  35244. }
  35245. var clipPlaneState = scene.clipPlane;
  35246. if (localOptions.clipPlane) {
  35247. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35248. }
  35249. if (_this.storeEffectOnSubMeshes) {
  35250. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35251. if (onCompiled) {
  35252. onCompiled(_this);
  35253. }
  35254. }
  35255. else {
  35256. setTimeout(checkReady, 16);
  35257. }
  35258. }
  35259. else {
  35260. if (_this.isReady(mesh)) {
  35261. if (onCompiled) {
  35262. onCompiled(_this);
  35263. }
  35264. }
  35265. else {
  35266. setTimeout(checkReady, 16);
  35267. }
  35268. }
  35269. if (localOptions.clipPlane) {
  35270. scene.clipPlane = clipPlaneState;
  35271. }
  35272. };
  35273. checkReady();
  35274. };
  35275. /**
  35276. * Force shader compilation
  35277. * @param mesh defines the mesh that will use this material
  35278. * @param options defines additional options for compiling the shaders
  35279. * @returns a promise that resolves when the compilation completes
  35280. */
  35281. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35282. var _this = this;
  35283. return new Promise(function (resolve) {
  35284. _this.forceCompilation(mesh, function () {
  35285. resolve();
  35286. }, options);
  35287. });
  35288. };
  35289. /**
  35290. * Marks a define in the material to indicate that it needs to be re-computed
  35291. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35292. */
  35293. Material.prototype.markAsDirty = function (flag) {
  35294. if (flag & Material.TextureDirtyFlag) {
  35295. this._markAllSubMeshesAsTexturesDirty();
  35296. }
  35297. if (flag & Material.LightDirtyFlag) {
  35298. this._markAllSubMeshesAsLightsDirty();
  35299. }
  35300. if (flag & Material.FresnelDirtyFlag) {
  35301. this._markAllSubMeshesAsFresnelDirty();
  35302. }
  35303. if (flag & Material.AttributesDirtyFlag) {
  35304. this._markAllSubMeshesAsAttributesDirty();
  35305. }
  35306. if (flag & Material.MiscDirtyFlag) {
  35307. this._markAllSubMeshesAsMiscDirty();
  35308. }
  35309. this.getScene().resetCachedMaterial();
  35310. };
  35311. /**
  35312. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35313. * @param func defines a function which checks material defines against the submeshes
  35314. */
  35315. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35316. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35317. var mesh = _a[_i];
  35318. if (!mesh.subMeshes) {
  35319. continue;
  35320. }
  35321. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35322. var subMesh = _c[_b];
  35323. if (subMesh.getMaterial() !== this) {
  35324. continue;
  35325. }
  35326. if (!subMesh._materialDefines) {
  35327. continue;
  35328. }
  35329. func(subMesh._materialDefines);
  35330. }
  35331. }
  35332. };
  35333. /**
  35334. * Indicates that image processing needs to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35338. };
  35339. /**
  35340. * Indicates that textures need to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35344. };
  35345. /**
  35346. * Indicates that fresnel needs to be re-calculated for all submeshes
  35347. */
  35348. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35350. };
  35351. /**
  35352. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35353. */
  35354. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35355. this._markAllSubMeshesAsDirty(function (defines) {
  35356. defines.markAsFresnelDirty();
  35357. defines.markAsMiscDirty();
  35358. });
  35359. };
  35360. /**
  35361. * Indicates that lights need to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that attributes need to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35371. };
  35372. /**
  35373. * Indicates that misc needs to be re-calculated for all submeshes
  35374. */
  35375. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35376. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35377. };
  35378. /**
  35379. * Indicates that textures and misc need to be re-calculated for all submeshes
  35380. */
  35381. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35382. this._markAllSubMeshesAsDirty(function (defines) {
  35383. defines.markAsTexturesDirty();
  35384. defines.markAsMiscDirty();
  35385. });
  35386. };
  35387. /**
  35388. * Disposes the material
  35389. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35390. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35391. */
  35392. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35393. // Animations
  35394. this.getScene().stopAnimation(this);
  35395. this.getScene().freeProcessedMaterials();
  35396. // Remove from scene
  35397. var index = this._scene.materials.indexOf(this);
  35398. if (index >= 0) {
  35399. this._scene.materials.splice(index, 1);
  35400. }
  35401. // Remove from meshes
  35402. for (index = 0; index < this._scene.meshes.length; index++) {
  35403. var mesh = this._scene.meshes[index];
  35404. if (mesh.material === this) {
  35405. mesh.material = null;
  35406. if (mesh.geometry) {
  35407. var geometry = (mesh.geometry);
  35408. if (this.storeEffectOnSubMeshes) {
  35409. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35410. var subMesh = _a[_i];
  35411. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35412. if (forceDisposeEffect && subMesh._materialEffect) {
  35413. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35414. }
  35415. }
  35416. }
  35417. else {
  35418. geometry._releaseVertexArrayObject(this._effect);
  35419. }
  35420. }
  35421. }
  35422. }
  35423. this._uniformBuffer.dispose();
  35424. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35425. if (forceDisposeEffect && this._effect) {
  35426. if (!this.storeEffectOnSubMeshes) {
  35427. this._scene.getEngine()._releaseEffect(this._effect);
  35428. }
  35429. this._effect = null;
  35430. }
  35431. // Callback
  35432. this.onDisposeObservable.notifyObservers(this);
  35433. this.onDisposeObservable.clear();
  35434. this.onBindObservable.clear();
  35435. this.onUnBindObservable.clear();
  35436. };
  35437. /**
  35438. * Serializes this material
  35439. * @returns the serialized material object
  35440. */
  35441. Material.prototype.serialize = function () {
  35442. return BABYLON.SerializationHelper.Serialize(this);
  35443. };
  35444. /**
  35445. * Creates a MultiMaterial from parsed MultiMaterial data.
  35446. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35447. * @param scene defines the hosting scene
  35448. * @returns a new MultiMaterial
  35449. */
  35450. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35451. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35452. multiMaterial.id = parsedMultiMaterial.id;
  35453. if (BABYLON.Tags) {
  35454. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35455. }
  35456. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35457. var subMatId = parsedMultiMaterial.materials[matIndex];
  35458. if (subMatId) {
  35459. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35460. }
  35461. else {
  35462. multiMaterial.subMaterials.push(null);
  35463. }
  35464. }
  35465. return multiMaterial;
  35466. };
  35467. /**
  35468. * Creates a material from parsed material data
  35469. * @param parsedMaterial defines parsed material data
  35470. * @param scene defines the hosting scene
  35471. * @param rootUrl defines the root URL to use to load textures
  35472. * @returns a new material
  35473. */
  35474. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35475. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35476. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35477. }
  35478. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35479. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35480. if (!BABYLON.LegacyPBRMaterial) {
  35481. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35482. return;
  35483. }
  35484. }
  35485. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35486. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35487. };
  35488. // Triangle views
  35489. Material._TriangleFillMode = 0;
  35490. Material._WireFrameFillMode = 1;
  35491. Material._PointFillMode = 2;
  35492. // Draw modes
  35493. Material._PointListDrawMode = 3;
  35494. Material._LineListDrawMode = 4;
  35495. Material._LineLoopDrawMode = 5;
  35496. Material._LineStripDrawMode = 6;
  35497. Material._TriangleStripDrawMode = 7;
  35498. Material._TriangleFanDrawMode = 8;
  35499. /**
  35500. * Stores the clock-wise side orientation
  35501. */
  35502. Material._ClockWiseSideOrientation = 0;
  35503. /**
  35504. * Stores the counter clock-wise side orientation
  35505. */
  35506. Material._CounterClockWiseSideOrientation = 1;
  35507. /**
  35508. * The dirty texture flag value
  35509. */
  35510. Material._TextureDirtyFlag = 1;
  35511. /**
  35512. * The dirty light flag value
  35513. */
  35514. Material._LightDirtyFlag = 2;
  35515. /**
  35516. * The dirty fresnel flag value
  35517. */
  35518. Material._FresnelDirtyFlag = 4;
  35519. /**
  35520. * The dirty attribute flag value
  35521. */
  35522. Material._AttributesDirtyFlag = 8;
  35523. /**
  35524. * The dirty misc flag value
  35525. */
  35526. Material._MiscDirtyFlag = 16;
  35527. __decorate([
  35528. BABYLON.serialize()
  35529. ], Material.prototype, "id", void 0);
  35530. __decorate([
  35531. BABYLON.serialize()
  35532. ], Material.prototype, "uniqueId", void 0);
  35533. __decorate([
  35534. BABYLON.serialize()
  35535. ], Material.prototype, "name", void 0);
  35536. __decorate([
  35537. BABYLON.serialize()
  35538. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35539. __decorate([
  35540. BABYLON.serialize()
  35541. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35542. __decorate([
  35543. BABYLON.serialize()
  35544. ], Material.prototype, "state", void 0);
  35545. __decorate([
  35546. BABYLON.serialize("alpha")
  35547. ], Material.prototype, "_alpha", void 0);
  35548. __decorate([
  35549. BABYLON.serialize("backFaceCulling")
  35550. ], Material.prototype, "_backFaceCulling", void 0);
  35551. __decorate([
  35552. BABYLON.serialize()
  35553. ], Material.prototype, "sideOrientation", void 0);
  35554. __decorate([
  35555. BABYLON.serialize("alphaMode")
  35556. ], Material.prototype, "_alphaMode", void 0);
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], Material.prototype, "_needDepthPrePass", void 0);
  35560. __decorate([
  35561. BABYLON.serialize()
  35562. ], Material.prototype, "disableDepthWrite", void 0);
  35563. __decorate([
  35564. BABYLON.serialize()
  35565. ], Material.prototype, "forceDepthWrite", void 0);
  35566. __decorate([
  35567. BABYLON.serialize()
  35568. ], Material.prototype, "separateCullingPass", void 0);
  35569. __decorate([
  35570. BABYLON.serialize("fogEnabled")
  35571. ], Material.prototype, "_fogEnabled", void 0);
  35572. __decorate([
  35573. BABYLON.serialize()
  35574. ], Material.prototype, "pointSize", void 0);
  35575. __decorate([
  35576. BABYLON.serialize()
  35577. ], Material.prototype, "zOffset", void 0);
  35578. __decorate([
  35579. BABYLON.serialize()
  35580. ], Material.prototype, "wireframe", null);
  35581. __decorate([
  35582. BABYLON.serialize()
  35583. ], Material.prototype, "pointsCloud", null);
  35584. __decorate([
  35585. BABYLON.serialize()
  35586. ], Material.prototype, "fillMode", null);
  35587. return Material;
  35588. }());
  35589. BABYLON.Material = Material;
  35590. })(BABYLON || (BABYLON = {}));
  35591. //# sourceMappingURL=babylon.material.js.map
  35592. var BABYLON;
  35593. (function (BABYLON) {
  35594. var UniformBuffer = /** @class */ (function () {
  35595. /**
  35596. * Uniform buffer objects.
  35597. *
  35598. * Handles blocks of uniform on the GPU.
  35599. *
  35600. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35601. *
  35602. * For more information, please refer to :
  35603. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35604. */
  35605. function UniformBuffer(engine, data, dynamic) {
  35606. this._engine = engine;
  35607. this._noUBO = !engine.supportsUniformBuffers;
  35608. this._dynamic = dynamic;
  35609. this._data = data || [];
  35610. this._uniformLocations = {};
  35611. this._uniformSizes = {};
  35612. this._uniformLocationPointer = 0;
  35613. this._needSync = false;
  35614. if (this._noUBO) {
  35615. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35616. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35617. this.updateFloat = this._updateFloatForEffect;
  35618. this.updateFloat2 = this._updateFloat2ForEffect;
  35619. this.updateFloat3 = this._updateFloat3ForEffect;
  35620. this.updateFloat4 = this._updateFloat4ForEffect;
  35621. this.updateMatrix = this._updateMatrixForEffect;
  35622. this.updateVector3 = this._updateVector3ForEffect;
  35623. this.updateVector4 = this._updateVector4ForEffect;
  35624. this.updateColor3 = this._updateColor3ForEffect;
  35625. this.updateColor4 = this._updateColor4ForEffect;
  35626. }
  35627. else {
  35628. this._engine._uniformBuffers.push(this);
  35629. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35630. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35631. this.updateFloat = this._updateFloatForUniform;
  35632. this.updateFloat2 = this._updateFloat2ForUniform;
  35633. this.updateFloat3 = this._updateFloat3ForUniform;
  35634. this.updateFloat4 = this._updateFloat4ForUniform;
  35635. this.updateMatrix = this._updateMatrixForUniform;
  35636. this.updateVector3 = this._updateVector3ForUniform;
  35637. this.updateVector4 = this._updateVector4ForUniform;
  35638. this.updateColor3 = this._updateColor3ForUniform;
  35639. this.updateColor4 = this._updateColor4ForUniform;
  35640. }
  35641. }
  35642. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35643. // Properties
  35644. /**
  35645. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35646. * or just falling back on setUniformXXX calls.
  35647. */
  35648. get: function () {
  35649. return !this._noUBO;
  35650. },
  35651. enumerable: true,
  35652. configurable: true
  35653. });
  35654. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35655. /**
  35656. * Indicates if the WebGL underlying uniform buffer is in sync
  35657. * with the javascript cache data.
  35658. */
  35659. get: function () {
  35660. return !this._needSync;
  35661. },
  35662. enumerable: true,
  35663. configurable: true
  35664. });
  35665. /**
  35666. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35667. * Also, a dynamic UniformBuffer will disable cache verification and always
  35668. * update the underlying WebGL uniform buffer to the GPU.
  35669. */
  35670. UniformBuffer.prototype.isDynamic = function () {
  35671. return this._dynamic !== undefined;
  35672. };
  35673. /**
  35674. * The data cache on JS side.
  35675. */
  35676. UniformBuffer.prototype.getData = function () {
  35677. return this._bufferData;
  35678. };
  35679. /**
  35680. * The underlying WebGL Uniform buffer.
  35681. */
  35682. UniformBuffer.prototype.getBuffer = function () {
  35683. return this._buffer;
  35684. };
  35685. /**
  35686. * std140 layout specifies how to align data within an UBO structure.
  35687. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35688. * for specs.
  35689. */
  35690. UniformBuffer.prototype._fillAlignment = function (size) {
  35691. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35692. // and 4x4 matrices
  35693. // TODO : change if other types are used
  35694. var alignment;
  35695. if (size <= 2) {
  35696. alignment = size;
  35697. }
  35698. else {
  35699. alignment = 4;
  35700. }
  35701. if ((this._uniformLocationPointer % alignment) !== 0) {
  35702. var oldPointer = this._uniformLocationPointer;
  35703. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35704. var diff = this._uniformLocationPointer - oldPointer;
  35705. for (var i = 0; i < diff; i++) {
  35706. this._data.push(0);
  35707. }
  35708. }
  35709. };
  35710. /**
  35711. * Adds an uniform in the buffer.
  35712. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35713. * for the layout to be correct !
  35714. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35715. * @param {number|number[]} size Data size, or data directly.
  35716. */
  35717. UniformBuffer.prototype.addUniform = function (name, size) {
  35718. if (this._noUBO) {
  35719. return;
  35720. }
  35721. if (this._uniformLocations[name] !== undefined) {
  35722. // Already existing uniform
  35723. return;
  35724. }
  35725. // This function must be called in the order of the shader layout !
  35726. // size can be the size of the uniform, or data directly
  35727. var data;
  35728. if (size instanceof Array) {
  35729. data = size;
  35730. size = data.length;
  35731. }
  35732. else {
  35733. size = size;
  35734. data = [];
  35735. // Fill with zeros
  35736. for (var i = 0; i < size; i++) {
  35737. data.push(0);
  35738. }
  35739. }
  35740. this._fillAlignment(size);
  35741. this._uniformSizes[name] = size;
  35742. this._uniformLocations[name] = this._uniformLocationPointer;
  35743. this._uniformLocationPointer += size;
  35744. for (var i = 0; i < size; i++) {
  35745. this._data.push(data[i]);
  35746. }
  35747. this._needSync = true;
  35748. };
  35749. /**
  35750. * Wrapper for addUniform.
  35751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35752. * @param {Matrix} mat A 4x4 matrix.
  35753. */
  35754. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35755. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35756. };
  35757. /**
  35758. * Wrapper for addUniform.
  35759. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35760. * @param {number} x
  35761. * @param {number} y
  35762. */
  35763. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35764. var temp = [x, y];
  35765. this.addUniform(name, temp);
  35766. };
  35767. /**
  35768. * Wrapper for addUniform.
  35769. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35770. * @param {number} x
  35771. * @param {number} y
  35772. * @param {number} z
  35773. */
  35774. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35775. var temp = [x, y, z];
  35776. this.addUniform(name, temp);
  35777. };
  35778. /**
  35779. * Wrapper for addUniform.
  35780. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35781. * @param {Color3} color
  35782. */
  35783. UniformBuffer.prototype.addColor3 = function (name, color) {
  35784. var temp = new Array();
  35785. color.toArray(temp);
  35786. this.addUniform(name, temp);
  35787. };
  35788. /**
  35789. * Wrapper for addUniform.
  35790. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35791. * @param {Color3} color
  35792. * @param {number} alpha
  35793. */
  35794. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35795. var temp = new Array();
  35796. color.toArray(temp);
  35797. temp.push(alpha);
  35798. this.addUniform(name, temp);
  35799. };
  35800. /**
  35801. * Wrapper for addUniform.
  35802. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35803. * @param {Vector3} vector
  35804. */
  35805. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35806. var temp = new Array();
  35807. vector.toArray(temp);
  35808. this.addUniform(name, temp);
  35809. };
  35810. /**
  35811. * Wrapper for addUniform.
  35812. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35813. */
  35814. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35815. this.addUniform(name, 12);
  35816. };
  35817. /**
  35818. * Wrapper for addUniform.
  35819. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35820. */
  35821. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35822. this.addUniform(name, 8);
  35823. };
  35824. /**
  35825. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35826. */
  35827. UniformBuffer.prototype.create = function () {
  35828. if (this._noUBO) {
  35829. return;
  35830. }
  35831. if (this._buffer) {
  35832. return; // nothing to do
  35833. }
  35834. // See spec, alignment must be filled as a vec4
  35835. this._fillAlignment(4);
  35836. this._bufferData = new Float32Array(this._data);
  35837. this._rebuild();
  35838. this._needSync = true;
  35839. };
  35840. UniformBuffer.prototype._rebuild = function () {
  35841. if (this._noUBO) {
  35842. return;
  35843. }
  35844. if (this._dynamic) {
  35845. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35846. }
  35847. else {
  35848. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35849. }
  35850. };
  35851. /**
  35852. * Updates the WebGL Uniform Buffer on the GPU.
  35853. * If the `dynamic` flag is set to true, no cache comparison is done.
  35854. * Otherwise, the buffer will be updated only if the cache differs.
  35855. */
  35856. UniformBuffer.prototype.update = function () {
  35857. if (!this._buffer) {
  35858. this.create();
  35859. return;
  35860. }
  35861. if (!this._dynamic && !this._needSync) {
  35862. return;
  35863. }
  35864. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35865. this._needSync = false;
  35866. };
  35867. /**
  35868. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35869. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35870. * @param {number[]|Float32Array} data Flattened data
  35871. * @param {number} size Size of the data.
  35872. */
  35873. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35874. var location = this._uniformLocations[uniformName];
  35875. if (location === undefined) {
  35876. if (this._buffer) {
  35877. // Cannot add an uniform if the buffer is already created
  35878. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35879. return;
  35880. }
  35881. this.addUniform(uniformName, size);
  35882. location = this._uniformLocations[uniformName];
  35883. }
  35884. if (!this._buffer) {
  35885. this.create();
  35886. }
  35887. if (!this._dynamic) {
  35888. // Cache for static uniform buffers
  35889. var changed = false;
  35890. for (var i = 0; i < size; i++) {
  35891. if (this._bufferData[location + i] !== data[i]) {
  35892. changed = true;
  35893. this._bufferData[location + i] = data[i];
  35894. }
  35895. }
  35896. this._needSync = this._needSync || changed;
  35897. }
  35898. else {
  35899. // No cache for dynamic
  35900. for (var i = 0; i < size; i++) {
  35901. this._bufferData[location + i] = data[i];
  35902. }
  35903. }
  35904. };
  35905. // Update methods
  35906. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35907. // To match std140, matrix must be realigned
  35908. for (var i = 0; i < 3; i++) {
  35909. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35910. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35911. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35912. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35913. }
  35914. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35915. };
  35916. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35917. this._currentEffect.setMatrix3x3(name, matrix);
  35918. };
  35919. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35920. this._currentEffect.setMatrix2x2(name, matrix);
  35921. };
  35922. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35923. // To match std140, matrix must be realigned
  35924. for (var i = 0; i < 2; i++) {
  35925. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35926. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35927. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35928. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35929. }
  35930. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35931. };
  35932. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35933. this._currentEffect.setFloat(name, x);
  35934. };
  35935. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35936. UniformBuffer._tempBuffer[0] = x;
  35937. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35938. };
  35939. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35940. if (suffix === void 0) { suffix = ""; }
  35941. this._currentEffect.setFloat2(name + suffix, x, y);
  35942. };
  35943. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35944. if (suffix === void 0) { suffix = ""; }
  35945. UniformBuffer._tempBuffer[0] = x;
  35946. UniformBuffer._tempBuffer[1] = y;
  35947. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35948. };
  35949. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35950. if (suffix === void 0) { suffix = ""; }
  35951. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35952. };
  35953. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35954. if (suffix === void 0) { suffix = ""; }
  35955. UniformBuffer._tempBuffer[0] = x;
  35956. UniformBuffer._tempBuffer[1] = y;
  35957. UniformBuffer._tempBuffer[2] = z;
  35958. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35959. };
  35960. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35961. if (suffix === void 0) { suffix = ""; }
  35962. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35963. };
  35964. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35965. if (suffix === void 0) { suffix = ""; }
  35966. UniformBuffer._tempBuffer[0] = x;
  35967. UniformBuffer._tempBuffer[1] = y;
  35968. UniformBuffer._tempBuffer[2] = z;
  35969. UniformBuffer._tempBuffer[3] = w;
  35970. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35971. };
  35972. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35973. this._currentEffect.setMatrix(name, mat);
  35974. };
  35975. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35976. this.updateUniform(name, mat.toArray(), 16);
  35977. };
  35978. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35979. this._currentEffect.setVector3(name, vector);
  35980. };
  35981. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35982. vector.toArray(UniformBuffer._tempBuffer);
  35983. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35984. };
  35985. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35986. this._currentEffect.setVector4(name, vector);
  35987. };
  35988. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35989. vector.toArray(UniformBuffer._tempBuffer);
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35991. };
  35992. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35993. if (suffix === void 0) { suffix = ""; }
  35994. this._currentEffect.setColor3(name + suffix, color);
  35995. };
  35996. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35997. if (suffix === void 0) { suffix = ""; }
  35998. color.toArray(UniformBuffer._tempBuffer);
  35999. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36000. };
  36001. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36002. if (suffix === void 0) { suffix = ""; }
  36003. this._currentEffect.setColor4(name + suffix, color, alpha);
  36004. };
  36005. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36006. if (suffix === void 0) { suffix = ""; }
  36007. color.toArray(UniformBuffer._tempBuffer);
  36008. UniformBuffer._tempBuffer[3] = alpha;
  36009. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36010. };
  36011. /**
  36012. * Sets a sampler uniform on the effect.
  36013. * @param {string} name Name of the sampler.
  36014. * @param {Texture} texture
  36015. */
  36016. UniformBuffer.prototype.setTexture = function (name, texture) {
  36017. this._currentEffect.setTexture(name, texture);
  36018. };
  36019. /**
  36020. * Directly updates the value of the uniform in the cache AND on the GPU.
  36021. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36022. * @param {number[]|Float32Array} data Flattened data
  36023. */
  36024. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36025. this.updateUniform(uniformName, data, data.length);
  36026. this.update();
  36027. };
  36028. /**
  36029. * Binds this uniform buffer to an effect.
  36030. * @param {Effect} effect
  36031. * @param {string} name Name of the uniform block in the shader.
  36032. */
  36033. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36034. this._currentEffect = effect;
  36035. if (this._noUBO || !this._buffer) {
  36036. return;
  36037. }
  36038. effect.bindUniformBuffer(this._buffer, name);
  36039. };
  36040. /**
  36041. * Disposes the uniform buffer.
  36042. */
  36043. UniformBuffer.prototype.dispose = function () {
  36044. if (this._noUBO) {
  36045. return;
  36046. }
  36047. var index = this._engine._uniformBuffers.indexOf(this);
  36048. if (index !== -1) {
  36049. this._engine._uniformBuffers.splice(index, 1);
  36050. }
  36051. if (!this._buffer) {
  36052. return;
  36053. }
  36054. if (this._engine._releaseBuffer(this._buffer)) {
  36055. this._buffer = null;
  36056. }
  36057. };
  36058. // Pool for avoiding memory leaks
  36059. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36060. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36061. return UniformBuffer;
  36062. }());
  36063. BABYLON.UniformBuffer = UniformBuffer;
  36064. })(BABYLON || (BABYLON = {}));
  36065. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36066. var BABYLON;
  36067. (function (BABYLON) {
  36068. /**
  36069. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36070. */
  36071. var VertexData = /** @class */ (function () {
  36072. function VertexData() {
  36073. }
  36074. /**
  36075. * Uses the passed data array to set the set the values for the specified kind of data
  36076. * @param data a linear array of floating numbers
  36077. * @param kind the type of data that is being set, eg positions, colors etc
  36078. */
  36079. VertexData.prototype.set = function (data, kind) {
  36080. switch (kind) {
  36081. case BABYLON.VertexBuffer.PositionKind:
  36082. this.positions = data;
  36083. break;
  36084. case BABYLON.VertexBuffer.NormalKind:
  36085. this.normals = data;
  36086. break;
  36087. case BABYLON.VertexBuffer.TangentKind:
  36088. this.tangents = data;
  36089. break;
  36090. case BABYLON.VertexBuffer.UVKind:
  36091. this.uvs = data;
  36092. break;
  36093. case BABYLON.VertexBuffer.UV2Kind:
  36094. this.uvs2 = data;
  36095. break;
  36096. case BABYLON.VertexBuffer.UV3Kind:
  36097. this.uvs3 = data;
  36098. break;
  36099. case BABYLON.VertexBuffer.UV4Kind:
  36100. this.uvs4 = data;
  36101. break;
  36102. case BABYLON.VertexBuffer.UV5Kind:
  36103. this.uvs5 = data;
  36104. break;
  36105. case BABYLON.VertexBuffer.UV6Kind:
  36106. this.uvs6 = data;
  36107. break;
  36108. case BABYLON.VertexBuffer.ColorKind:
  36109. this.colors = data;
  36110. break;
  36111. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36112. this.matricesIndices = data;
  36113. break;
  36114. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36115. this.matricesWeights = data;
  36116. break;
  36117. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36118. this.matricesIndicesExtra = data;
  36119. break;
  36120. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36121. this.matricesWeightsExtra = data;
  36122. break;
  36123. }
  36124. };
  36125. /**
  36126. * Associates the vertexData to the passed Mesh.
  36127. * Sets it as updatable or not (default `false`)
  36128. * @param mesh the mesh the vertexData is applied to
  36129. * @param updatable when used and having the value true allows new data to update the vertexData
  36130. * @returns the VertexData
  36131. */
  36132. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36133. this._applyTo(mesh, updatable);
  36134. return this;
  36135. };
  36136. /**
  36137. * Associates the vertexData to the passed Geometry.
  36138. * Sets it as updatable or not (default `false`)
  36139. * @param geometry the geometry the vertexData is applied to
  36140. * @param updatable when used and having the value true allows new data to update the vertexData
  36141. * @returns VertexData
  36142. */
  36143. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36144. this._applyTo(geometry, updatable);
  36145. return this;
  36146. };
  36147. /**
  36148. * Updates the associated mesh
  36149. * @param mesh the mesh to be updated
  36150. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36151. * @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
  36152. * @returns VertexData
  36153. */
  36154. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36155. this._update(mesh);
  36156. return this;
  36157. };
  36158. /**
  36159. * Updates the associated geometry
  36160. * @param geometry the geometry to be updated
  36161. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36162. * @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
  36163. * @returns VertexData.
  36164. */
  36165. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36166. this._update(geometry);
  36167. return this;
  36168. };
  36169. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36170. if (updatable === void 0) { updatable = false; }
  36171. if (this.positions) {
  36172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36173. }
  36174. if (this.normals) {
  36175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36176. }
  36177. if (this.tangents) {
  36178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36179. }
  36180. if (this.uvs) {
  36181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36182. }
  36183. if (this.uvs2) {
  36184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36185. }
  36186. if (this.uvs3) {
  36187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36188. }
  36189. if (this.uvs4) {
  36190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36191. }
  36192. if (this.uvs5) {
  36193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36194. }
  36195. if (this.uvs6) {
  36196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36197. }
  36198. if (this.colors) {
  36199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36200. }
  36201. if (this.matricesIndices) {
  36202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36203. }
  36204. if (this.matricesWeights) {
  36205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36206. }
  36207. if (this.matricesIndicesExtra) {
  36208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36209. }
  36210. if (this.matricesWeightsExtra) {
  36211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36212. }
  36213. if (this.indices) {
  36214. meshOrGeometry.setIndices(this.indices, null, updatable);
  36215. }
  36216. else {
  36217. meshOrGeometry.setIndices([], null);
  36218. }
  36219. return this;
  36220. };
  36221. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36222. if (this.positions) {
  36223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36224. }
  36225. if (this.normals) {
  36226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36227. }
  36228. if (this.tangents) {
  36229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36230. }
  36231. if (this.uvs) {
  36232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36233. }
  36234. if (this.uvs2) {
  36235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36236. }
  36237. if (this.uvs3) {
  36238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36239. }
  36240. if (this.uvs4) {
  36241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36242. }
  36243. if (this.uvs5) {
  36244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36245. }
  36246. if (this.uvs6) {
  36247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36248. }
  36249. if (this.colors) {
  36250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36251. }
  36252. if (this.matricesIndices) {
  36253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36254. }
  36255. if (this.matricesWeights) {
  36256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36257. }
  36258. if (this.matricesIndicesExtra) {
  36259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36260. }
  36261. if (this.matricesWeightsExtra) {
  36262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36263. }
  36264. if (this.indices) {
  36265. meshOrGeometry.setIndices(this.indices, null);
  36266. }
  36267. return this;
  36268. };
  36269. /**
  36270. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36271. * @param matrix the transforming matrix
  36272. * @returns the VertexData
  36273. */
  36274. VertexData.prototype.transform = function (matrix) {
  36275. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36276. var transformed = BABYLON.Vector3.Zero();
  36277. var index;
  36278. if (this.positions) {
  36279. var position = BABYLON.Vector3.Zero();
  36280. for (index = 0; index < this.positions.length; index += 3) {
  36281. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36282. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36283. this.positions[index] = transformed.x;
  36284. this.positions[index + 1] = transformed.y;
  36285. this.positions[index + 2] = transformed.z;
  36286. }
  36287. }
  36288. if (this.normals) {
  36289. var normal = BABYLON.Vector3.Zero();
  36290. for (index = 0; index < this.normals.length; index += 3) {
  36291. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36292. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36293. this.normals[index] = transformed.x;
  36294. this.normals[index + 1] = transformed.y;
  36295. this.normals[index + 2] = transformed.z;
  36296. }
  36297. }
  36298. if (this.tangents) {
  36299. var tangent = BABYLON.Vector4.Zero();
  36300. var tangentTransformed = BABYLON.Vector4.Zero();
  36301. for (index = 0; index < this.tangents.length; index += 4) {
  36302. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36303. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36304. this.tangents[index] = tangentTransformed.x;
  36305. this.tangents[index + 1] = tangentTransformed.y;
  36306. this.tangents[index + 2] = tangentTransformed.z;
  36307. this.tangents[index + 3] = tangentTransformed.w;
  36308. }
  36309. }
  36310. if (flip && this.indices) {
  36311. for (index = 0; index < this.indices.length; index += 3) {
  36312. var tmp = this.indices[index + 1];
  36313. this.indices[index + 1] = this.indices[index + 2];
  36314. this.indices[index + 2] = tmp;
  36315. }
  36316. }
  36317. return this;
  36318. };
  36319. /**
  36320. * Merges the passed VertexData into the current one
  36321. * @param other the VertexData to be merged into the current one
  36322. * @returns the modified VertexData
  36323. */
  36324. VertexData.prototype.merge = function (other) {
  36325. this._validate();
  36326. other._validate();
  36327. if (!this.normals !== !other.normals ||
  36328. !this.tangents !== !other.tangents ||
  36329. !this.uvs !== !other.uvs ||
  36330. !this.uvs2 !== !other.uvs2 ||
  36331. !this.uvs3 !== !other.uvs3 ||
  36332. !this.uvs4 !== !other.uvs4 ||
  36333. !this.uvs5 !== !other.uvs5 ||
  36334. !this.uvs6 !== !other.uvs6 ||
  36335. !this.colors !== !other.colors ||
  36336. !this.matricesIndices !== !other.matricesIndices ||
  36337. !this.matricesWeights !== !other.matricesWeights ||
  36338. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36339. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36340. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36341. }
  36342. if (other.indices) {
  36343. if (!this.indices) {
  36344. this.indices = [];
  36345. }
  36346. var offset = this.positions ? this.positions.length / 3 : 0;
  36347. for (var index = 0; index < other.indices.length; index++) {
  36348. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36349. this.indices.push(other.indices[index] + offset);
  36350. }
  36351. }
  36352. this.positions = this._mergeElement(this.positions, other.positions);
  36353. this.normals = this._mergeElement(this.normals, other.normals);
  36354. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36355. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36356. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36357. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36358. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36359. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36360. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36361. this.colors = this._mergeElement(this.colors, other.colors);
  36362. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36363. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36364. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36365. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36366. return this;
  36367. };
  36368. VertexData.prototype._mergeElement = function (source, other) {
  36369. if (!source) {
  36370. return other;
  36371. }
  36372. if (!other) {
  36373. return source;
  36374. }
  36375. var len = other.length + source.length;
  36376. var isSrcTypedArray = source instanceof Float32Array;
  36377. var isOthTypedArray = other instanceof Float32Array;
  36378. // use non-loop method when the source is Float32Array
  36379. if (isSrcTypedArray) {
  36380. var ret32 = new Float32Array(len);
  36381. ret32.set(source);
  36382. ret32.set(other, source.length);
  36383. return ret32;
  36384. // source is number[], when other is also use concat
  36385. }
  36386. else if (!isOthTypedArray) {
  36387. return source.concat(other);
  36388. // source is a number[], but other is a Float32Array, loop required
  36389. }
  36390. else {
  36391. var ret = source.slice(0); // copy source to a separate array
  36392. for (var i = 0, len = other.length; i < len; i++) {
  36393. ret.push(other[i]);
  36394. }
  36395. return ret;
  36396. }
  36397. };
  36398. VertexData.prototype._validate = function () {
  36399. if (!this.positions) {
  36400. throw new Error("Positions are required");
  36401. }
  36402. var getElementCount = function (kind, values) {
  36403. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36404. if ((values.length % stride) !== 0) {
  36405. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36406. }
  36407. return values.length / stride;
  36408. };
  36409. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36410. var validateElementCount = function (kind, values) {
  36411. var elementCount = getElementCount(kind, values);
  36412. if (elementCount !== positionsElementCount) {
  36413. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36414. }
  36415. };
  36416. if (this.normals)
  36417. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36418. if (this.tangents)
  36419. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36420. if (this.uvs)
  36421. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36422. if (this.uvs2)
  36423. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36424. if (this.uvs3)
  36425. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36426. if (this.uvs4)
  36427. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36428. if (this.uvs5)
  36429. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36430. if (this.uvs6)
  36431. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36432. if (this.colors)
  36433. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36434. if (this.matricesIndices)
  36435. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36436. if (this.matricesWeights)
  36437. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36438. if (this.matricesIndicesExtra)
  36439. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36440. if (this.matricesWeightsExtra)
  36441. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36442. };
  36443. /**
  36444. * Serializes the VertexData
  36445. * @returns a serialized object
  36446. */
  36447. VertexData.prototype.serialize = function () {
  36448. var serializationObject = this.serialize();
  36449. if (this.positions) {
  36450. serializationObject.positions = this.positions;
  36451. }
  36452. if (this.normals) {
  36453. serializationObject.normals = this.normals;
  36454. }
  36455. if (this.tangents) {
  36456. serializationObject.tangents = this.tangents;
  36457. }
  36458. if (this.uvs) {
  36459. serializationObject.uvs = this.uvs;
  36460. }
  36461. if (this.uvs2) {
  36462. serializationObject.uvs2 = this.uvs2;
  36463. }
  36464. if (this.uvs3) {
  36465. serializationObject.uvs3 = this.uvs3;
  36466. }
  36467. if (this.uvs4) {
  36468. serializationObject.uvs4 = this.uvs4;
  36469. }
  36470. if (this.uvs5) {
  36471. serializationObject.uvs5 = this.uvs5;
  36472. }
  36473. if (this.uvs6) {
  36474. serializationObject.uvs6 = this.uvs6;
  36475. }
  36476. if (this.colors) {
  36477. serializationObject.colors = this.colors;
  36478. }
  36479. if (this.matricesIndices) {
  36480. serializationObject.matricesIndices = this.matricesIndices;
  36481. serializationObject.matricesIndices._isExpanded = true;
  36482. }
  36483. if (this.matricesWeights) {
  36484. serializationObject.matricesWeights = this.matricesWeights;
  36485. }
  36486. if (this.matricesIndicesExtra) {
  36487. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36488. serializationObject.matricesIndicesExtra._isExpanded = true;
  36489. }
  36490. if (this.matricesWeightsExtra) {
  36491. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36492. }
  36493. serializationObject.indices = this.indices;
  36494. return serializationObject;
  36495. };
  36496. // Statics
  36497. /**
  36498. * Extracts the vertexData from a mesh
  36499. * @param mesh the mesh from which to extract the VertexData
  36500. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36501. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36502. * @returns the object VertexData associated to the passed mesh
  36503. */
  36504. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36505. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36506. };
  36507. /**
  36508. * Extracts the vertexData from the geometry
  36509. * @param geometry the geometry from which to extract the VertexData
  36510. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36511. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36512. * @returns the object VertexData associated to the passed mesh
  36513. */
  36514. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36515. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36516. };
  36517. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36518. var result = new VertexData();
  36519. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36520. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36521. }
  36522. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36523. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36524. }
  36525. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36526. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36527. }
  36528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36529. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36530. }
  36531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36532. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36533. }
  36534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36535. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36536. }
  36537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36538. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36539. }
  36540. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36541. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36542. }
  36543. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36544. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36545. }
  36546. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36547. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36548. }
  36549. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36550. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36551. }
  36552. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36553. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36554. }
  36555. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36556. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36557. }
  36558. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36559. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36560. }
  36561. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36562. return result;
  36563. };
  36564. /**
  36565. * Creates the VertexData for a Ribbon
  36566. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36567. * * pathArray array of paths, each of which an array of successive Vector3
  36568. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36569. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36570. * * 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
  36571. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36572. * * 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)
  36573. * * 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)
  36574. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36575. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36576. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36577. * @returns the VertexData of the ribbon
  36578. */
  36579. VertexData.CreateRibbon = function (options) {
  36580. var pathArray = options.pathArray;
  36581. var closeArray = options.closeArray || false;
  36582. var closePath = options.closePath || false;
  36583. var invertUV = options.invertUV || false;
  36584. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36585. var offset = options.offset || defaultOffset;
  36586. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36587. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36588. var customUV = options.uvs;
  36589. var customColors = options.colors;
  36590. var positions = [];
  36591. var indices = [];
  36592. var normals = [];
  36593. var uvs = [];
  36594. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36595. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36596. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36597. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36598. var minlg; // minimal length among all paths from pathArray
  36599. var lg = []; // array of path lengths : nb of vertex per path
  36600. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36601. var p; // path iterator
  36602. var i; // point iterator
  36603. var j; // point iterator
  36604. // if single path in pathArray
  36605. if (pathArray.length < 2) {
  36606. var ar1 = [];
  36607. var ar2 = [];
  36608. for (i = 0; i < pathArray[0].length - offset; i++) {
  36609. ar1.push(pathArray[0][i]);
  36610. ar2.push(pathArray[0][i + offset]);
  36611. }
  36612. pathArray = [ar1, ar2];
  36613. }
  36614. // positions and horizontal distances (u)
  36615. var idc = 0;
  36616. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36617. var path;
  36618. var l;
  36619. minlg = pathArray[0].length;
  36620. var vectlg;
  36621. var dist;
  36622. for (p = 0; p < pathArray.length; p++) {
  36623. uTotalDistance[p] = 0;
  36624. us[p] = [0];
  36625. path = pathArray[p];
  36626. l = path.length;
  36627. minlg = (minlg < l) ? minlg : l;
  36628. j = 0;
  36629. while (j < l) {
  36630. positions.push(path[j].x, path[j].y, path[j].z);
  36631. if (j > 0) {
  36632. vectlg = path[j].subtract(path[j - 1]).length();
  36633. dist = vectlg + uTotalDistance[p];
  36634. us[p].push(dist);
  36635. uTotalDistance[p] = dist;
  36636. }
  36637. j++;
  36638. }
  36639. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36640. j--;
  36641. positions.push(path[0].x, path[0].y, path[0].z);
  36642. vectlg = path[j].subtract(path[0]).length();
  36643. dist = vectlg + uTotalDistance[p];
  36644. us[p].push(dist);
  36645. uTotalDistance[p] = dist;
  36646. }
  36647. lg[p] = l + closePathCorr;
  36648. idx[p] = idc;
  36649. idc += (l + closePathCorr);
  36650. }
  36651. // vertical distances (v)
  36652. var path1;
  36653. var path2;
  36654. var vertex1 = null;
  36655. var vertex2 = null;
  36656. for (i = 0; i < minlg + closePathCorr; i++) {
  36657. vTotalDistance[i] = 0;
  36658. vs[i] = [0];
  36659. for (p = 0; p < pathArray.length - 1; p++) {
  36660. path1 = pathArray[p];
  36661. path2 = pathArray[p + 1];
  36662. if (i === minlg) { // closePath
  36663. vertex1 = path1[0];
  36664. vertex2 = path2[0];
  36665. }
  36666. else {
  36667. vertex1 = path1[i];
  36668. vertex2 = path2[i];
  36669. }
  36670. vectlg = vertex2.subtract(vertex1).length();
  36671. dist = vectlg + vTotalDistance[i];
  36672. vs[i].push(dist);
  36673. vTotalDistance[i] = dist;
  36674. }
  36675. if (closeArray && vertex2 && vertex1) {
  36676. path1 = pathArray[p];
  36677. path2 = pathArray[0];
  36678. if (i === minlg) { // closePath
  36679. vertex2 = path2[0];
  36680. }
  36681. vectlg = vertex2.subtract(vertex1).length();
  36682. dist = vectlg + vTotalDistance[i];
  36683. vTotalDistance[i] = dist;
  36684. }
  36685. }
  36686. // uvs
  36687. var u;
  36688. var v;
  36689. if (customUV) {
  36690. for (p = 0; p < customUV.length; p++) {
  36691. uvs.push(customUV[p].x, customUV[p].y);
  36692. }
  36693. }
  36694. else {
  36695. for (p = 0; p < pathArray.length; p++) {
  36696. for (i = 0; i < minlg + closePathCorr; i++) {
  36697. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36698. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36699. if (invertUV) {
  36700. uvs.push(v, u);
  36701. }
  36702. else {
  36703. uvs.push(u, v);
  36704. }
  36705. }
  36706. }
  36707. }
  36708. // indices
  36709. p = 0; // path index
  36710. var pi = 0; // positions array index
  36711. var l1 = lg[p] - 1; // path1 length
  36712. var l2 = lg[p + 1] - 1; // path2 length
  36713. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36714. var shft = idx[1] - idx[0]; // shift
  36715. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36716. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36717. // 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
  36718. indices.push(pi, pi + shft, pi + 1);
  36719. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36720. pi += 1;
  36721. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36722. p++;
  36723. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36724. shft = idx[0] - idx[p];
  36725. l1 = lg[p] - 1;
  36726. l2 = lg[0] - 1;
  36727. }
  36728. else {
  36729. shft = idx[p + 1] - idx[p];
  36730. l1 = lg[p] - 1;
  36731. l2 = lg[p + 1] - 1;
  36732. }
  36733. pi = idx[p];
  36734. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36735. }
  36736. }
  36737. // normals
  36738. VertexData.ComputeNormals(positions, indices, normals);
  36739. if (closePath) { // update both the first and last vertex normals to their average value
  36740. var indexFirst = 0;
  36741. var indexLast = 0;
  36742. for (p = 0; p < pathArray.length; p++) {
  36743. indexFirst = idx[p] * 3;
  36744. if (p + 1 < pathArray.length) {
  36745. indexLast = (idx[p + 1] - 1) * 3;
  36746. }
  36747. else {
  36748. indexLast = normals.length - 3;
  36749. }
  36750. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36751. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36752. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36753. normals[indexLast] = normals[indexFirst];
  36754. normals[indexLast + 1] = normals[indexFirst + 1];
  36755. normals[indexLast + 2] = normals[indexFirst + 2];
  36756. }
  36757. }
  36758. // sides
  36759. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36760. // Colors
  36761. var colors = null;
  36762. if (customColors) {
  36763. colors = new Float32Array(customColors.length * 4);
  36764. for (var c = 0; c < customColors.length; c++) {
  36765. colors[c * 4] = customColors[c].r;
  36766. colors[c * 4 + 1] = customColors[c].g;
  36767. colors[c * 4 + 2] = customColors[c].b;
  36768. colors[c * 4 + 3] = customColors[c].a;
  36769. }
  36770. }
  36771. // Result
  36772. var vertexData = new VertexData();
  36773. var positions32 = new Float32Array(positions);
  36774. var normals32 = new Float32Array(normals);
  36775. var uvs32 = new Float32Array(uvs);
  36776. vertexData.indices = indices;
  36777. vertexData.positions = positions32;
  36778. vertexData.normals = normals32;
  36779. vertexData.uvs = uvs32;
  36780. if (colors) {
  36781. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36782. }
  36783. if (closePath) {
  36784. vertexData._idx = idx;
  36785. }
  36786. return vertexData;
  36787. };
  36788. /**
  36789. * Creates the VertexData for a box
  36790. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36791. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36792. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36793. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36794. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36795. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36796. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36797. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36798. * * 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)
  36799. * * 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)
  36800. * @returns the VertexData of the box
  36801. */
  36802. VertexData.CreateBox = function (options) {
  36803. var normalsSource = [
  36804. new BABYLON.Vector3(0, 0, 1),
  36805. new BABYLON.Vector3(0, 0, -1),
  36806. new BABYLON.Vector3(1, 0, 0),
  36807. new BABYLON.Vector3(-1, 0, 0),
  36808. new BABYLON.Vector3(0, 1, 0),
  36809. new BABYLON.Vector3(0, -1, 0)
  36810. ];
  36811. var indices = [];
  36812. var positions = [];
  36813. var normals = [];
  36814. var uvs = [];
  36815. var width = options.width || options.size || 1;
  36816. var height = options.height || options.size || 1;
  36817. var depth = options.depth || options.size || 1;
  36818. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36819. var faceUV = options.faceUV || new Array(6);
  36820. var faceColors = options.faceColors;
  36821. var colors = [];
  36822. // default face colors and UV if undefined
  36823. for (var f = 0; f < 6; f++) {
  36824. if (faceUV[f] === undefined) {
  36825. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36826. }
  36827. if (faceColors && faceColors[f] === undefined) {
  36828. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36829. }
  36830. }
  36831. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36832. // Create each face in turn.
  36833. for (var index = 0; index < normalsSource.length; index++) {
  36834. var normal = normalsSource[index];
  36835. // Get two vectors perpendicular to the face normal and to each other.
  36836. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36837. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36838. // Six indices (two triangles) per face.
  36839. var verticesLength = positions.length / 3;
  36840. indices.push(verticesLength);
  36841. indices.push(verticesLength + 1);
  36842. indices.push(verticesLength + 2);
  36843. indices.push(verticesLength);
  36844. indices.push(verticesLength + 2);
  36845. indices.push(verticesLength + 3);
  36846. // Four vertices per face.
  36847. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36848. positions.push(vertex.x, vertex.y, vertex.z);
  36849. normals.push(normal.x, normal.y, normal.z);
  36850. uvs.push(faceUV[index].z, faceUV[index].w);
  36851. if (faceColors) {
  36852. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36853. }
  36854. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36855. positions.push(vertex.x, vertex.y, vertex.z);
  36856. normals.push(normal.x, normal.y, normal.z);
  36857. uvs.push(faceUV[index].x, faceUV[index].w);
  36858. if (faceColors) {
  36859. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36860. }
  36861. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36862. positions.push(vertex.x, vertex.y, vertex.z);
  36863. normals.push(normal.x, normal.y, normal.z);
  36864. uvs.push(faceUV[index].x, faceUV[index].y);
  36865. if (faceColors) {
  36866. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36867. }
  36868. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36869. positions.push(vertex.x, vertex.y, vertex.z);
  36870. normals.push(normal.x, normal.y, normal.z);
  36871. uvs.push(faceUV[index].z, faceUV[index].y);
  36872. if (faceColors) {
  36873. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36874. }
  36875. }
  36876. // sides
  36877. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36878. // Result
  36879. var vertexData = new VertexData();
  36880. vertexData.indices = indices;
  36881. vertexData.positions = positions;
  36882. vertexData.normals = normals;
  36883. vertexData.uvs = uvs;
  36884. if (faceColors) {
  36885. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36886. vertexData.colors = totalColors;
  36887. }
  36888. return vertexData;
  36889. };
  36890. /**
  36891. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36892. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36893. * * segments sets the number of horizontal strips optional, default 32
  36894. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36895. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36896. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36897. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36898. * * 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
  36899. * * 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
  36900. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36901. * * 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)
  36902. * * 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)
  36903. * @returns the VertexData of the ellipsoid
  36904. */
  36905. VertexData.CreateSphere = function (options) {
  36906. var segments = options.segments || 32;
  36907. var diameterX = options.diameterX || options.diameter || 1;
  36908. var diameterY = options.diameterY || options.diameter || 1;
  36909. var diameterZ = options.diameterZ || options.diameter || 1;
  36910. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36911. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36912. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36913. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36914. var totalZRotationSteps = 2 + segments;
  36915. var totalYRotationSteps = 2 * totalZRotationSteps;
  36916. var indices = [];
  36917. var positions = [];
  36918. var normals = [];
  36919. var uvs = [];
  36920. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36921. var normalizedZ = zRotationStep / totalZRotationSteps;
  36922. var angleZ = normalizedZ * Math.PI * slice;
  36923. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36924. var normalizedY = yRotationStep / totalYRotationSteps;
  36925. var angleY = normalizedY * Math.PI * 2 * arc;
  36926. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36927. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36928. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36929. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36930. var vertex = complete.multiply(radius);
  36931. var normal = complete.divide(radius).normalize();
  36932. positions.push(vertex.x, vertex.y, vertex.z);
  36933. normals.push(normal.x, normal.y, normal.z);
  36934. uvs.push(normalizedY, normalizedZ);
  36935. }
  36936. if (zRotationStep > 0) {
  36937. var verticesCount = positions.length / 3;
  36938. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36939. indices.push((firstIndex));
  36940. indices.push((firstIndex + 1));
  36941. indices.push(firstIndex + totalYRotationSteps + 1);
  36942. indices.push((firstIndex + totalYRotationSteps + 1));
  36943. indices.push((firstIndex + 1));
  36944. indices.push((firstIndex + totalYRotationSteps + 2));
  36945. }
  36946. }
  36947. }
  36948. // Sides
  36949. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36950. // Result
  36951. var vertexData = new VertexData();
  36952. vertexData.indices = indices;
  36953. vertexData.positions = positions;
  36954. vertexData.normals = normals;
  36955. vertexData.uvs = uvs;
  36956. return vertexData;
  36957. };
  36958. /**
  36959. * Creates the VertexData for a cylinder, cone or prism
  36960. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36961. * * height sets the height (y direction) of the cylinder, optional, default 2
  36962. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36963. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36964. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36965. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36966. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36967. * * 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
  36968. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36969. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36970. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36971. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36972. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36973. * * 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)
  36974. * * 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)
  36975. * @returns the VertexData of the cylinder, cone or prism
  36976. */
  36977. VertexData.CreateCylinder = function (options) {
  36978. var height = options.height || 2;
  36979. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36980. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36981. var tessellation = options.tessellation || 24;
  36982. var subdivisions = options.subdivisions || 1;
  36983. var hasRings = options.hasRings ? true : false;
  36984. var enclose = options.enclose ? true : false;
  36985. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36986. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36987. var faceUV = options.faceUV || new Array(3);
  36988. var faceColors = options.faceColors;
  36989. // default face colors and UV if undefined
  36990. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36991. var ringNb = (hasRings) ? subdivisions : 1;
  36992. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36993. var f;
  36994. for (f = 0; f < surfaceNb; f++) {
  36995. if (faceColors && faceColors[f] === undefined) {
  36996. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36997. }
  36998. }
  36999. for (f = 0; f < surfaceNb; f++) {
  37000. if (faceUV && faceUV[f] === undefined) {
  37001. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37002. }
  37003. }
  37004. var indices = new Array();
  37005. var positions = new Array();
  37006. var normals = new Array();
  37007. var uvs = new Array();
  37008. var colors = new Array();
  37009. var angle_step = Math.PI * 2 * arc / tessellation;
  37010. var angle;
  37011. var h;
  37012. var radius;
  37013. var tan = (diameterBottom - diameterTop) / 2 / height;
  37014. var ringVertex = BABYLON.Vector3.Zero();
  37015. var ringNormal = BABYLON.Vector3.Zero();
  37016. var ringFirstVertex = BABYLON.Vector3.Zero();
  37017. var ringFirstNormal = BABYLON.Vector3.Zero();
  37018. var quadNormal = BABYLON.Vector3.Zero();
  37019. var Y = BABYLON.Axis.Y;
  37020. // positions, normals, uvs
  37021. var i;
  37022. var j;
  37023. var r;
  37024. var ringIdx = 1;
  37025. var s = 1; // surface index
  37026. var cs = 0;
  37027. var v = 0;
  37028. for (i = 0; i <= subdivisions; i++) {
  37029. h = i / subdivisions;
  37030. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37031. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37032. for (r = 0; r < ringIdx; r++) {
  37033. if (hasRings) {
  37034. s += r;
  37035. }
  37036. if (enclose) {
  37037. s += 2 * r;
  37038. }
  37039. for (j = 0; j <= tessellation; j++) {
  37040. angle = j * angle_step;
  37041. // position
  37042. ringVertex.x = Math.cos(-angle) * radius;
  37043. ringVertex.y = -height / 2 + h * height;
  37044. ringVertex.z = Math.sin(-angle) * radius;
  37045. // normal
  37046. if (diameterTop === 0 && i === subdivisions) {
  37047. // if no top cap, reuse former normals
  37048. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37049. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37050. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37051. }
  37052. else {
  37053. ringNormal.x = ringVertex.x;
  37054. ringNormal.z = ringVertex.z;
  37055. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37056. ringNormal.normalize();
  37057. }
  37058. // keep first ring vertex values for enclose
  37059. if (j === 0) {
  37060. ringFirstVertex.copyFrom(ringVertex);
  37061. ringFirstNormal.copyFrom(ringNormal);
  37062. }
  37063. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37064. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37065. if (hasRings) {
  37066. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37067. }
  37068. else {
  37069. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37070. }
  37071. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37072. if (faceColors) {
  37073. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37074. }
  37075. }
  37076. // if enclose, add four vertices and their dedicated normals
  37077. if (arc !== 1 && enclose) {
  37078. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37079. positions.push(0, ringVertex.y, 0);
  37080. positions.push(0, ringVertex.y, 0);
  37081. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37082. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37083. quadNormal.normalize();
  37084. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37085. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37086. quadNormal.normalize();
  37087. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37088. if (hasRings) {
  37089. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37090. }
  37091. else {
  37092. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37093. }
  37094. uvs.push(faceUV[s + 1].x, v);
  37095. uvs.push(faceUV[s + 1].z, v);
  37096. if (hasRings) {
  37097. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37098. }
  37099. else {
  37100. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37101. }
  37102. uvs.push(faceUV[s + 2].x, v);
  37103. uvs.push(faceUV[s + 2].z, v);
  37104. if (faceColors) {
  37105. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37106. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37107. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37108. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37109. }
  37110. }
  37111. if (cs !== s) {
  37112. cs = s;
  37113. }
  37114. }
  37115. }
  37116. // indices
  37117. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37118. var s;
  37119. i = 0;
  37120. for (s = 0; s < subdivisions; s++) {
  37121. var i0 = 0;
  37122. var i1 = 0;
  37123. var i2 = 0;
  37124. var i3 = 0;
  37125. for (j = 0; j < tessellation; j++) {
  37126. i0 = i * (e + 1) + j;
  37127. i1 = (i + 1) * (e + 1) + j;
  37128. i2 = i * (e + 1) + (j + 1);
  37129. i3 = (i + 1) * (e + 1) + (j + 1);
  37130. indices.push(i0, i1, i2);
  37131. indices.push(i3, i2, i1);
  37132. }
  37133. if (arc !== 1 && enclose) { // if enclose, add two quads
  37134. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37135. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37136. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37137. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37138. }
  37139. i = (hasRings) ? (i + 2) : (i + 1);
  37140. }
  37141. // Caps
  37142. var createCylinderCap = function (isTop) {
  37143. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37144. if (radius === 0) {
  37145. return;
  37146. }
  37147. // Cap positions, normals & uvs
  37148. var angle;
  37149. var circleVector;
  37150. var i;
  37151. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37152. var c = null;
  37153. if (faceColors) {
  37154. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37155. }
  37156. // cap center
  37157. var vbase = positions.length / 3;
  37158. var offset = isTop ? height / 2 : -height / 2;
  37159. var center = new BABYLON.Vector3(0, offset, 0);
  37160. positions.push(center.x, center.y, center.z);
  37161. normals.push(0, isTop ? 1 : -1, 0);
  37162. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37163. if (c) {
  37164. colors.push(c.r, c.g, c.b, c.a);
  37165. }
  37166. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37167. for (i = 0; i <= tessellation; i++) {
  37168. angle = Math.PI * 2 * i * arc / tessellation;
  37169. var cos = Math.cos(-angle);
  37170. var sin = Math.sin(-angle);
  37171. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37172. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37173. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37174. normals.push(0, isTop ? 1 : -1, 0);
  37175. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37176. if (c) {
  37177. colors.push(c.r, c.g, c.b, c.a);
  37178. }
  37179. }
  37180. // Cap indices
  37181. for (i = 0; i < tessellation; i++) {
  37182. if (!isTop) {
  37183. indices.push(vbase);
  37184. indices.push(vbase + (i + 1));
  37185. indices.push(vbase + (i + 2));
  37186. }
  37187. else {
  37188. indices.push(vbase);
  37189. indices.push(vbase + (i + 2));
  37190. indices.push(vbase + (i + 1));
  37191. }
  37192. }
  37193. };
  37194. // add caps to geometry
  37195. createCylinderCap(false);
  37196. createCylinderCap(true);
  37197. // Sides
  37198. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37199. var vertexData = new VertexData();
  37200. vertexData.indices = indices;
  37201. vertexData.positions = positions;
  37202. vertexData.normals = normals;
  37203. vertexData.uvs = uvs;
  37204. if (faceColors) {
  37205. vertexData.colors = colors;
  37206. }
  37207. return vertexData;
  37208. };
  37209. /**
  37210. * Creates the VertexData for a torus
  37211. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37212. * * diameter the diameter of the torus, optional default 1
  37213. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37214. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37215. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37216. * * 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)
  37217. * * 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)
  37218. * @returns the VertexData of the torus
  37219. */
  37220. VertexData.CreateTorus = function (options) {
  37221. var indices = [];
  37222. var positions = [];
  37223. var normals = [];
  37224. var uvs = [];
  37225. var diameter = options.diameter || 1;
  37226. var thickness = options.thickness || 0.5;
  37227. var tessellation = options.tessellation || 16;
  37228. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37229. var stride = tessellation + 1;
  37230. for (var i = 0; i <= tessellation; i++) {
  37231. var u = i / tessellation;
  37232. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37233. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37234. for (var j = 0; j <= tessellation; j++) {
  37235. var v = 1 - j / tessellation;
  37236. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37237. var dx = Math.cos(innerAngle);
  37238. var dy = Math.sin(innerAngle);
  37239. // Create a vertex.
  37240. var normal = new BABYLON.Vector3(dx, dy, 0);
  37241. var position = normal.scale(thickness / 2);
  37242. var textureCoordinate = new BABYLON.Vector2(u, v);
  37243. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37244. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37245. positions.push(position.x, position.y, position.z);
  37246. normals.push(normal.x, normal.y, normal.z);
  37247. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37248. // And create indices for two triangles.
  37249. var nextI = (i + 1) % stride;
  37250. var nextJ = (j + 1) % stride;
  37251. indices.push(i * stride + j);
  37252. indices.push(i * stride + nextJ);
  37253. indices.push(nextI * stride + j);
  37254. indices.push(i * stride + nextJ);
  37255. indices.push(nextI * stride + nextJ);
  37256. indices.push(nextI * stride + j);
  37257. }
  37258. }
  37259. // Sides
  37260. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37261. // Result
  37262. var vertexData = new VertexData();
  37263. vertexData.indices = indices;
  37264. vertexData.positions = positions;
  37265. vertexData.normals = normals;
  37266. vertexData.uvs = uvs;
  37267. return vertexData;
  37268. };
  37269. /**
  37270. * Creates the VertexData of the LineSystem
  37271. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37272. * - lines an array of lines, each line being an array of successive Vector3
  37273. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37274. * @returns the VertexData of the LineSystem
  37275. */
  37276. VertexData.CreateLineSystem = function (options) {
  37277. var indices = [];
  37278. var positions = [];
  37279. var lines = options.lines;
  37280. var colors = options.colors;
  37281. var vertexColors = [];
  37282. var idx = 0;
  37283. for (var l = 0; l < lines.length; l++) {
  37284. var points = lines[l];
  37285. for (var index = 0; index < points.length; index++) {
  37286. positions.push(points[index].x, points[index].y, points[index].z);
  37287. if (colors) {
  37288. var color = colors[l];
  37289. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37290. }
  37291. if (index > 0) {
  37292. indices.push(idx - 1);
  37293. indices.push(idx);
  37294. }
  37295. idx++;
  37296. }
  37297. }
  37298. var vertexData = new VertexData();
  37299. vertexData.indices = indices;
  37300. vertexData.positions = positions;
  37301. if (colors) {
  37302. vertexData.colors = vertexColors;
  37303. }
  37304. return vertexData;
  37305. };
  37306. /**
  37307. * Create the VertexData for a DashedLines
  37308. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37309. * - points an array successive Vector3
  37310. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37311. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37312. * - dashNb the intended total number of dashes, optional, default 200
  37313. * @returns the VertexData for the DashedLines
  37314. */
  37315. VertexData.CreateDashedLines = function (options) {
  37316. var dashSize = options.dashSize || 3;
  37317. var gapSize = options.gapSize || 1;
  37318. var dashNb = options.dashNb || 200;
  37319. var points = options.points;
  37320. var positions = new Array();
  37321. var indices = new Array();
  37322. var curvect = BABYLON.Vector3.Zero();
  37323. var lg = 0;
  37324. var nb = 0;
  37325. var shft = 0;
  37326. var dashshft = 0;
  37327. var curshft = 0;
  37328. var idx = 0;
  37329. var i = 0;
  37330. for (i = 0; i < points.length - 1; i++) {
  37331. points[i + 1].subtractToRef(points[i], curvect);
  37332. lg += curvect.length();
  37333. }
  37334. shft = lg / dashNb;
  37335. dashshft = dashSize * shft / (dashSize + gapSize);
  37336. for (i = 0; i < points.length - 1; i++) {
  37337. points[i + 1].subtractToRef(points[i], curvect);
  37338. nb = Math.floor(curvect.length() / shft);
  37339. curvect.normalize();
  37340. for (var j = 0; j < nb; j++) {
  37341. curshft = shft * j;
  37342. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37343. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37344. indices.push(idx, idx + 1);
  37345. idx += 2;
  37346. }
  37347. }
  37348. // Result
  37349. var vertexData = new VertexData();
  37350. vertexData.positions = positions;
  37351. vertexData.indices = indices;
  37352. return vertexData;
  37353. };
  37354. /**
  37355. * Creates the VertexData for a Ground
  37356. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37357. * - width the width (x direction) of the ground, optional, default 1
  37358. * - height the height (z direction) of the ground, optional, default 1
  37359. * - subdivisions the number of subdivisions per side, optional, default 1
  37360. * @returns the VertexData of the Ground
  37361. */
  37362. VertexData.CreateGround = function (options) {
  37363. var indices = [];
  37364. var positions = [];
  37365. var normals = [];
  37366. var uvs = [];
  37367. var row, col;
  37368. var width = options.width || 1;
  37369. var height = options.height || 1;
  37370. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37371. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37372. for (row = 0; row <= subdivisionsY; row++) {
  37373. for (col = 0; col <= subdivisionsX; col++) {
  37374. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37375. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37376. positions.push(position.x, position.y, position.z);
  37377. normals.push(normal.x, normal.y, normal.z);
  37378. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37379. }
  37380. }
  37381. for (row = 0; row < subdivisionsY; row++) {
  37382. for (col = 0; col < subdivisionsX; col++) {
  37383. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37384. indices.push(col + 1 + row * (subdivisionsX + 1));
  37385. indices.push(col + row * (subdivisionsX + 1));
  37386. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37387. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37388. indices.push(col + row * (subdivisionsX + 1));
  37389. }
  37390. }
  37391. // Result
  37392. var vertexData = new VertexData();
  37393. vertexData.indices = indices;
  37394. vertexData.positions = positions;
  37395. vertexData.normals = normals;
  37396. vertexData.uvs = uvs;
  37397. return vertexData;
  37398. };
  37399. /**
  37400. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37401. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37402. * * xmin the ground minimum X coordinate, optional, default -1
  37403. * * zmin the ground minimum Z coordinate, optional, default -1
  37404. * * xmax the ground maximum X coordinate, optional, default 1
  37405. * * zmax the ground maximum Z coordinate, optional, default 1
  37406. * * 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}
  37407. * * 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}
  37408. * @returns the VertexData of the TiledGround
  37409. */
  37410. VertexData.CreateTiledGround = function (options) {
  37411. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37412. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37413. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37414. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37415. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37416. var precision = options.precision || { w: 1, h: 1 };
  37417. var indices = new Array();
  37418. var positions = new Array();
  37419. var normals = new Array();
  37420. var uvs = new Array();
  37421. var row, col, tileRow, tileCol;
  37422. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37423. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37424. precision.w = (precision.w < 1) ? 1 : precision.w;
  37425. precision.h = (precision.h < 1) ? 1 : precision.h;
  37426. var tileSize = {
  37427. 'w': (xmax - xmin) / subdivisions.w,
  37428. 'h': (zmax - zmin) / subdivisions.h
  37429. };
  37430. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37431. // Indices
  37432. var base = positions.length / 3;
  37433. var rowLength = precision.w + 1;
  37434. for (row = 0; row < precision.h; row++) {
  37435. for (col = 0; col < precision.w; col++) {
  37436. var square = [
  37437. base + col + row * rowLength,
  37438. base + (col + 1) + row * rowLength,
  37439. base + (col + 1) + (row + 1) * rowLength,
  37440. base + col + (row + 1) * rowLength
  37441. ];
  37442. indices.push(square[1]);
  37443. indices.push(square[2]);
  37444. indices.push(square[3]);
  37445. indices.push(square[0]);
  37446. indices.push(square[1]);
  37447. indices.push(square[3]);
  37448. }
  37449. }
  37450. // Position, normals and uvs
  37451. var position = BABYLON.Vector3.Zero();
  37452. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37453. for (row = 0; row <= precision.h; row++) {
  37454. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37455. for (col = 0; col <= precision.w; col++) {
  37456. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37457. position.y = 0;
  37458. positions.push(position.x, position.y, position.z);
  37459. normals.push(normal.x, normal.y, normal.z);
  37460. uvs.push(col / precision.w, row / precision.h);
  37461. }
  37462. }
  37463. }
  37464. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37465. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37466. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37467. }
  37468. }
  37469. // Result
  37470. var vertexData = new VertexData();
  37471. vertexData.indices = indices;
  37472. vertexData.positions = positions;
  37473. vertexData.normals = normals;
  37474. vertexData.uvs = uvs;
  37475. return vertexData;
  37476. };
  37477. /**
  37478. * Creates the VertexData of the Ground designed from a heightmap
  37479. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37480. * * width the width (x direction) of the ground
  37481. * * height the height (z direction) of the ground
  37482. * * subdivisions the number of subdivisions per side
  37483. * * minHeight the minimum altitude on the ground, optional, default 0
  37484. * * maxHeight the maximum altitude on the ground, optional default 1
  37485. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37486. * * buffer the array holding the image color data
  37487. * * bufferWidth the width of image
  37488. * * bufferHeight the height of image
  37489. * @returns the VertexData of the Ground designed from a heightmap
  37490. */
  37491. VertexData.CreateGroundFromHeightMap = function (options) {
  37492. var indices = [];
  37493. var positions = [];
  37494. var normals = [];
  37495. var uvs = [];
  37496. var row, col;
  37497. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37498. // Vertices
  37499. for (row = 0; row <= options.subdivisions; row++) {
  37500. for (col = 0; col <= options.subdivisions; col++) {
  37501. 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));
  37502. // Compute height
  37503. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37504. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37505. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37506. var r = options.buffer[pos] / 255.0;
  37507. var g = options.buffer[pos + 1] / 255.0;
  37508. var b = options.buffer[pos + 2] / 255.0;
  37509. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37510. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37511. // Add vertex
  37512. positions.push(position.x, position.y, position.z);
  37513. normals.push(0, 0, 0);
  37514. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37515. }
  37516. }
  37517. // Indices
  37518. for (row = 0; row < options.subdivisions; row++) {
  37519. for (col = 0; col < options.subdivisions; col++) {
  37520. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37521. indices.push(col + 1 + row * (options.subdivisions + 1));
  37522. indices.push(col + row * (options.subdivisions + 1));
  37523. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37524. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37525. indices.push(col + row * (options.subdivisions + 1));
  37526. }
  37527. }
  37528. // Normals
  37529. VertexData.ComputeNormals(positions, indices, normals);
  37530. // Result
  37531. var vertexData = new VertexData();
  37532. vertexData.indices = indices;
  37533. vertexData.positions = positions;
  37534. vertexData.normals = normals;
  37535. vertexData.uvs = uvs;
  37536. return vertexData;
  37537. };
  37538. /**
  37539. * Creates the VertexData for a Plane
  37540. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37541. * * size sets the width and height of the plane to the value of size, optional default 1
  37542. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37543. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37544. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37545. * * 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)
  37546. * * 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)
  37547. * @returns the VertexData of the box
  37548. */
  37549. VertexData.CreatePlane = function (options) {
  37550. var indices = [];
  37551. var positions = [];
  37552. var normals = [];
  37553. var uvs = [];
  37554. var width = options.width || options.size || 1;
  37555. var height = options.height || options.size || 1;
  37556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37557. // Vertices
  37558. var halfWidth = width / 2.0;
  37559. var halfHeight = height / 2.0;
  37560. positions.push(-halfWidth, -halfHeight, 0);
  37561. normals.push(0, 0, -1.0);
  37562. uvs.push(0.0, 0.0);
  37563. positions.push(halfWidth, -halfHeight, 0);
  37564. normals.push(0, 0, -1.0);
  37565. uvs.push(1.0, 0.0);
  37566. positions.push(halfWidth, halfHeight, 0);
  37567. normals.push(0, 0, -1.0);
  37568. uvs.push(1.0, 1.0);
  37569. positions.push(-halfWidth, halfHeight, 0);
  37570. normals.push(0, 0, -1.0);
  37571. uvs.push(0.0, 1.0);
  37572. // Indices
  37573. indices.push(0);
  37574. indices.push(1);
  37575. indices.push(2);
  37576. indices.push(0);
  37577. indices.push(2);
  37578. indices.push(3);
  37579. // Sides
  37580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37581. // Result
  37582. var vertexData = new VertexData();
  37583. vertexData.indices = indices;
  37584. vertexData.positions = positions;
  37585. vertexData.normals = normals;
  37586. vertexData.uvs = uvs;
  37587. return vertexData;
  37588. };
  37589. /**
  37590. * Creates the VertexData of the Disc or regular Polygon
  37591. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37592. * * radius the radius of the disc, optional default 0.5
  37593. * * tessellation the number of polygon sides, optional, default 64
  37594. * * 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
  37595. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37596. * * 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)
  37597. * * 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)
  37598. * @returns the VertexData of the box
  37599. */
  37600. VertexData.CreateDisc = function (options) {
  37601. var positions = new Array();
  37602. var indices = new Array();
  37603. var normals = new Array();
  37604. var uvs = new Array();
  37605. var radius = options.radius || 0.5;
  37606. var tessellation = options.tessellation || 64;
  37607. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37608. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37609. // positions and uvs
  37610. positions.push(0, 0, 0); // disc center first
  37611. uvs.push(0.5, 0.5);
  37612. var theta = Math.PI * 2 * arc;
  37613. var step = theta / tessellation;
  37614. for (var a = 0; a < theta; a += step) {
  37615. var x = Math.cos(a);
  37616. var y = Math.sin(a);
  37617. var u = (x + 1) / 2;
  37618. var v = (1 - y) / 2;
  37619. positions.push(radius * x, radius * y, 0);
  37620. uvs.push(u, v);
  37621. }
  37622. if (arc === 1) {
  37623. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37624. uvs.push(uvs[2], uvs[3]);
  37625. }
  37626. //indices
  37627. var vertexNb = positions.length / 3;
  37628. for (var i = 1; i < vertexNb - 1; i++) {
  37629. indices.push(i + 1, 0, i);
  37630. }
  37631. // result
  37632. VertexData.ComputeNormals(positions, indices, normals);
  37633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37634. var vertexData = new VertexData();
  37635. vertexData.indices = indices;
  37636. vertexData.positions = positions;
  37637. vertexData.normals = normals;
  37638. vertexData.uvs = uvs;
  37639. return vertexData;
  37640. };
  37641. /**
  37642. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37643. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37644. * @param polygon a mesh built from polygonTriangulation.build()
  37645. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37646. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37647. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37648. * @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)
  37649. * @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)
  37650. * @returns the VertexData of the Polygon
  37651. */
  37652. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37653. var faceUV = fUV || new Array(3);
  37654. var faceColors = fColors;
  37655. var colors = [];
  37656. // default face colors and UV if undefined
  37657. for (var f = 0; f < 3; f++) {
  37658. if (faceUV[f] === undefined) {
  37659. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37660. }
  37661. if (faceColors && faceColors[f] === undefined) {
  37662. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37663. }
  37664. }
  37665. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37666. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37667. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37668. var indices = polygon.getIndices();
  37669. // set face colours and textures
  37670. var idx = 0;
  37671. var face = 0;
  37672. for (var index = 0; index < normals.length; index += 3) {
  37673. //Edge Face no. 1
  37674. if (Math.abs(normals[index + 1]) < 0.001) {
  37675. face = 1;
  37676. }
  37677. //Top Face no. 0
  37678. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37679. face = 0;
  37680. }
  37681. //Bottom Face no. 2
  37682. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37683. face = 2;
  37684. }
  37685. idx = index / 3;
  37686. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37687. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37688. if (faceColors) {
  37689. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37690. }
  37691. }
  37692. // sides
  37693. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37694. // Result
  37695. var vertexData = new VertexData();
  37696. vertexData.indices = indices;
  37697. vertexData.positions = positions;
  37698. vertexData.normals = normals;
  37699. vertexData.uvs = uvs;
  37700. if (faceColors) {
  37701. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37702. vertexData.colors = totalColors;
  37703. }
  37704. return vertexData;
  37705. };
  37706. /**
  37707. * Creates the VertexData of the IcoSphere
  37708. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37709. * * radius the radius of the IcoSphere, optional default 1
  37710. * * radiusX allows stretching in the x direction, optional, default radius
  37711. * * radiusY allows stretching in the y direction, optional, default radius
  37712. * * radiusZ allows stretching in the z direction, optional, default radius
  37713. * * flat when true creates a flat shaded mesh, optional, default true
  37714. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37715. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37716. * * 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)
  37717. * * 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)
  37718. * @returns the VertexData of the IcoSphere
  37719. */
  37720. VertexData.CreateIcoSphere = function (options) {
  37721. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37722. var radius = options.radius || 1;
  37723. var flat = (options.flat === undefined) ? true : options.flat;
  37724. var subdivisions = options.subdivisions || 4;
  37725. var radiusX = options.radiusX || radius;
  37726. var radiusY = options.radiusY || radius;
  37727. var radiusZ = options.radiusZ || radius;
  37728. var t = (1 + Math.sqrt(5)) / 2;
  37729. // 12 vertex x,y,z
  37730. var ico_vertices = [
  37731. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37732. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37733. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37734. ];
  37735. // index of 3 vertex makes a face of icopshere
  37736. var ico_indices = [
  37737. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37738. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37739. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37740. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37741. ];
  37742. // vertex for uv have aliased position, not for UV
  37743. var vertices_unalias_id = [
  37744. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37745. // vertex alias
  37746. 0,
  37747. 2,
  37748. 3,
  37749. 3,
  37750. 3,
  37751. 4,
  37752. 7,
  37753. 8,
  37754. 9,
  37755. 9,
  37756. 10,
  37757. 11 // 23: B + 12
  37758. ];
  37759. // uv as integer step (not pixels !)
  37760. var ico_vertexuv = [
  37761. 5, 1, 3, 1, 6, 4, 0, 0,
  37762. 5, 3, 4, 2, 2, 2, 4, 0,
  37763. 2, 0, 1, 1, 6, 0, 6, 2,
  37764. // vertex alias (for same vertex on different faces)
  37765. 0, 4,
  37766. 3, 3,
  37767. 4, 4,
  37768. 3, 1,
  37769. 4, 2,
  37770. 4, 4,
  37771. 0, 2,
  37772. 1, 1,
  37773. 2, 2,
  37774. 3, 3,
  37775. 1, 3,
  37776. 2, 4 // 23: B + 12
  37777. ];
  37778. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37779. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37780. // First island of uv mapping
  37781. // v = 4h 3+ 2
  37782. // v = 3h 9+ 4
  37783. // v = 2h 9+ 5 B
  37784. // v = 1h 9 1 0
  37785. // v = 0h 3 8 7 A
  37786. // u = 0 1 2 3 4 5 6 *a
  37787. // Second island of uv mapping
  37788. // v = 4h 0+ B+ 4+
  37789. // v = 3h A+ 2+
  37790. // v = 2h 7+ 6 3+
  37791. // v = 1h 8+ 3+
  37792. // v = 0h
  37793. // u = 0 1 2 3 4 5 6 *a
  37794. // Face layout on texture UV mapping
  37795. // ============
  37796. // \ 4 /\ 16 / ======
  37797. // \ / \ / /\ 11 /
  37798. // \/ 7 \/ / \ /
  37799. // ======= / 10 \/
  37800. // /\ 17 /\ =======
  37801. // / \ / \ \ 15 /\
  37802. // / 8 \/ 12 \ \ / \
  37803. // ============ \/ 6 \
  37804. // \ 18 /\ ============
  37805. // \ / \ \ 5 /\ 0 /
  37806. // \/ 13 \ \ / \ /
  37807. // ======= \/ 1 \/
  37808. // =============
  37809. // /\ 19 /\ 2 /\
  37810. // / \ / \ / \
  37811. // / 14 \/ 9 \/ 3 \
  37812. // ===================
  37813. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37814. var ustep = 138 / 1024;
  37815. var vstep = 239 / 1024;
  37816. var uoffset = 60 / 1024;
  37817. var voffset = 26 / 1024;
  37818. // Second island should have margin, not to touch the first island
  37819. // avoid any borderline artefact in pixel rounding
  37820. var island_u_offset = -40 / 1024;
  37821. var island_v_offset = +20 / 1024;
  37822. // face is either island 0 or 1 :
  37823. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37824. var island = [
  37825. 0, 0, 0, 0, 1,
  37826. 0, 0, 1, 1, 0,
  37827. 0, 0, 1, 1, 0,
  37828. 0, 1, 1, 1, 0 // 15 - 19
  37829. ];
  37830. var indices = new Array();
  37831. var positions = new Array();
  37832. var normals = new Array();
  37833. var uvs = new Array();
  37834. var current_indice = 0;
  37835. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37836. var face_vertex_pos = new Array(3);
  37837. var face_vertex_uv = new Array(3);
  37838. var v012;
  37839. for (v012 = 0; v012 < 3; v012++) {
  37840. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37841. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37842. }
  37843. // create all with normals
  37844. for (var face = 0; face < 20; face++) {
  37845. // 3 vertex per face
  37846. for (v012 = 0; v012 < 3; v012++) {
  37847. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37848. var v_id = ico_indices[3 * face + v012];
  37849. // vertex have 3D position (x,y,z)
  37850. 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]);
  37851. // Normalize to get normal, then scale to radius
  37852. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37853. // uv Coordinates from vertex ID
  37854. 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);
  37855. }
  37856. // Subdivide the face (interpolate pos, norm, uv)
  37857. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37858. // - norm is linear interpolation of vertex corner normal
  37859. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37860. // - uv is linear interpolation
  37861. //
  37862. // Topology is as below for sub-divide by 2
  37863. // vertex shown as v0,v1,v2
  37864. // interp index is i1 to progress in range [v0,v1[
  37865. // interp index is i2 to progress in range [v0,v2[
  37866. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37867. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37868. //
  37869. //
  37870. // i2 v2
  37871. // ^ ^
  37872. // / / \
  37873. // / / \
  37874. // / / \
  37875. // / / (0,1) \
  37876. // / #---------\
  37877. // / / \ (0,0)'/ \
  37878. // / / \ / \
  37879. // / / \ / \
  37880. // / / (0,0) \ / (1,0) \
  37881. // / #---------#---------\
  37882. // v0 v1
  37883. //
  37884. // --------------------> i1
  37885. //
  37886. // interp of (i1,i2):
  37887. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37888. // along i1 : lerp(x0,x1, i1/(S-i2))
  37889. //
  37890. // centroid of triangle is needed to get help normal computation
  37891. // (c1,c2) are used for centroid location
  37892. var interp_vertex = function (i1, i2, c1, c2) {
  37893. // vertex is interpolated from
  37894. // - face_vertex_pos[0..2]
  37895. // - face_vertex_uv[0..2]
  37896. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37897. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37898. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37899. pos_interp.normalize();
  37900. var vertex_normal;
  37901. if (flat) {
  37902. // in flat mode, recalculate normal as face centroid normal
  37903. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37904. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37905. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37906. }
  37907. else {
  37908. // in smooth mode, recalculate normal from each single vertex position
  37909. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37910. }
  37911. // Vertex normal need correction due to X,Y,Z radius scaling
  37912. vertex_normal.x /= radiusX;
  37913. vertex_normal.y /= radiusY;
  37914. vertex_normal.z /= radiusZ;
  37915. vertex_normal.normalize();
  37916. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37917. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37918. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37919. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37920. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37921. uvs.push(uv_interp.x, uv_interp.y);
  37922. // push each vertex has member of a face
  37923. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37924. indices.push(current_indice);
  37925. current_indice++;
  37926. };
  37927. for (var i2 = 0; i2 < subdivisions; i2++) {
  37928. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37929. // face : (i1,i2) for /\ :
  37930. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37931. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37932. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37933. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37934. if (i1 + i2 + 1 < subdivisions) {
  37935. // face : (i1,i2)' for \/ :
  37936. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37937. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37938. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37939. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37940. }
  37941. }
  37942. }
  37943. }
  37944. // Sides
  37945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37946. // Result
  37947. var vertexData = new VertexData();
  37948. vertexData.indices = indices;
  37949. vertexData.positions = positions;
  37950. vertexData.normals = normals;
  37951. vertexData.uvs = uvs;
  37952. return vertexData;
  37953. };
  37954. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37955. /**
  37956. * Creates the VertexData for a Polyhedron
  37957. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37958. * * type provided types are:
  37959. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37960. * * 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)
  37961. * * size the size of the IcoSphere, optional default 1
  37962. * * sizeX allows stretching in the x direction, optional, default size
  37963. * * sizeY allows stretching in the y direction, optional, default size
  37964. * * sizeZ allows stretching in the z direction, optional, default size
  37965. * * 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
  37966. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37967. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37968. * * flat when true creates a flat shaded mesh, optional, default true
  37969. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37970. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37971. * * 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)
  37972. * * 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)
  37973. * @returns the VertexData of the Polyhedron
  37974. */
  37975. VertexData.CreatePolyhedron = function (options) {
  37976. // provided polyhedron types :
  37977. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37978. // 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)
  37979. var polyhedra = [];
  37980. 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]] };
  37981. 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]] };
  37982. polyhedra[2] = {
  37983. 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]],
  37984. 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]]
  37985. };
  37986. polyhedra[3] = {
  37987. 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]],
  37988. 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]]
  37989. };
  37990. polyhedra[4] = {
  37991. 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]],
  37992. 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]]
  37993. };
  37994. 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]] };
  37995. 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]] };
  37996. 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]] };
  37997. 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]] };
  37998. 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]] };
  37999. 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]] };
  38000. 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]] };
  38001. 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]] };
  38002. 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]] };
  38003. polyhedra[14] = {
  38004. 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]],
  38005. 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]]
  38006. };
  38007. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38008. var size = options.size;
  38009. var sizeX = options.sizeX || size || 1;
  38010. var sizeY = options.sizeY || size || 1;
  38011. var sizeZ = options.sizeZ || size || 1;
  38012. var data = options.custom || polyhedra[type];
  38013. var nbfaces = data.face.length;
  38014. var faceUV = options.faceUV || new Array(nbfaces);
  38015. var faceColors = options.faceColors;
  38016. var flat = (options.flat === undefined) ? true : options.flat;
  38017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38018. var positions = new Array();
  38019. var indices = new Array();
  38020. var normals = new Array();
  38021. var uvs = new Array();
  38022. var colors = new Array();
  38023. var index = 0;
  38024. var faceIdx = 0; // face cursor in the array "indexes"
  38025. var indexes = new Array();
  38026. var i = 0;
  38027. var f = 0;
  38028. var u, v, ang, x, y, tmp;
  38029. // default face colors and UV if undefined
  38030. if (flat) {
  38031. for (f = 0; f < nbfaces; f++) {
  38032. if (faceColors && faceColors[f] === undefined) {
  38033. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38034. }
  38035. if (faceUV && faceUV[f] === undefined) {
  38036. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38037. }
  38038. }
  38039. }
  38040. if (!flat) {
  38041. for (i = 0; i < data.vertex.length; i++) {
  38042. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38043. uvs.push(0, 0);
  38044. }
  38045. for (f = 0; f < nbfaces; f++) {
  38046. for (i = 0; i < data.face[f].length - 2; i++) {
  38047. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38048. }
  38049. }
  38050. }
  38051. else {
  38052. for (f = 0; f < nbfaces; f++) {
  38053. var fl = data.face[f].length; // number of vertices of the current face
  38054. ang = 2 * Math.PI / fl;
  38055. x = 0.5 * Math.tan(ang / 2);
  38056. y = 0.5;
  38057. // positions, uvs, colors
  38058. for (i = 0; i < fl; i++) {
  38059. // positions
  38060. 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);
  38061. indexes.push(index);
  38062. index++;
  38063. // uvs
  38064. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38065. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38066. uvs.push(u, v);
  38067. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38068. y = x * Math.sin(ang) + y * Math.cos(ang);
  38069. x = tmp;
  38070. // colors
  38071. if (faceColors) {
  38072. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38073. }
  38074. }
  38075. // indices from indexes
  38076. for (i = 0; i < fl - 2; i++) {
  38077. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38078. }
  38079. faceIdx += fl;
  38080. }
  38081. }
  38082. VertexData.ComputeNormals(positions, indices, normals);
  38083. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38084. var vertexData = new VertexData();
  38085. vertexData.positions = positions;
  38086. vertexData.indices = indices;
  38087. vertexData.normals = normals;
  38088. vertexData.uvs = uvs;
  38089. if (faceColors && flat) {
  38090. vertexData.colors = colors;
  38091. }
  38092. return vertexData;
  38093. };
  38094. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38095. /**
  38096. * Creates the VertexData for a TorusKnot
  38097. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38098. * * radius the radius of the torus knot, optional, default 2
  38099. * * tube the thickness of the tube, optional, default 0.5
  38100. * * radialSegments the number of sides on each tube segments, optional, default 32
  38101. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38102. * * p the number of windings around the z axis, optional, default 2
  38103. * * q the number of windings around the x axis, optional, default 3
  38104. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38105. * * 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)
  38106. * * 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)
  38107. * @returns the VertexData of the Torus Knot
  38108. */
  38109. VertexData.CreateTorusKnot = function (options) {
  38110. var indices = new Array();
  38111. var positions = new Array();
  38112. var normals = new Array();
  38113. var uvs = new Array();
  38114. var radius = options.radius || 2;
  38115. var tube = options.tube || 0.5;
  38116. var radialSegments = options.radialSegments || 32;
  38117. var tubularSegments = options.tubularSegments || 32;
  38118. var p = options.p || 2;
  38119. var q = options.q || 3;
  38120. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38121. // Helper
  38122. var getPos = function (angle) {
  38123. var cu = Math.cos(angle);
  38124. var su = Math.sin(angle);
  38125. var quOverP = q / p * angle;
  38126. var cs = Math.cos(quOverP);
  38127. var tx = radius * (2 + cs) * 0.5 * cu;
  38128. var ty = radius * (2 + cs) * su * 0.5;
  38129. var tz = radius * Math.sin(quOverP) * 0.5;
  38130. return new BABYLON.Vector3(tx, ty, tz);
  38131. };
  38132. // Vertices
  38133. var i;
  38134. var j;
  38135. for (i = 0; i <= radialSegments; i++) {
  38136. var modI = i % radialSegments;
  38137. var u = modI / radialSegments * 2 * p * Math.PI;
  38138. var p1 = getPos(u);
  38139. var p2 = getPos(u + 0.01);
  38140. var tang = p2.subtract(p1);
  38141. var n = p2.add(p1);
  38142. var bitan = BABYLON.Vector3.Cross(tang, n);
  38143. n = BABYLON.Vector3.Cross(bitan, tang);
  38144. bitan.normalize();
  38145. n.normalize();
  38146. for (j = 0; j < tubularSegments; j++) {
  38147. var modJ = j % tubularSegments;
  38148. var v = modJ / tubularSegments * 2 * Math.PI;
  38149. var cx = -tube * Math.cos(v);
  38150. var cy = tube * Math.sin(v);
  38151. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38152. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38153. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38154. uvs.push(i / radialSegments);
  38155. uvs.push(j / tubularSegments);
  38156. }
  38157. }
  38158. for (i = 0; i < radialSegments; i++) {
  38159. for (j = 0; j < tubularSegments; j++) {
  38160. var jNext = (j + 1) % tubularSegments;
  38161. var a = i * tubularSegments + j;
  38162. var b = (i + 1) * tubularSegments + j;
  38163. var c = (i + 1) * tubularSegments + jNext;
  38164. var d = i * tubularSegments + jNext;
  38165. indices.push(d);
  38166. indices.push(b);
  38167. indices.push(a);
  38168. indices.push(d);
  38169. indices.push(c);
  38170. indices.push(b);
  38171. }
  38172. }
  38173. // Normals
  38174. VertexData.ComputeNormals(positions, indices, normals);
  38175. // Sides
  38176. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38177. // Result
  38178. var vertexData = new VertexData();
  38179. vertexData.indices = indices;
  38180. vertexData.positions = positions;
  38181. vertexData.normals = normals;
  38182. vertexData.uvs = uvs;
  38183. return vertexData;
  38184. };
  38185. // Tools
  38186. /**
  38187. * Compute normals for given positions and indices
  38188. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38189. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38190. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38191. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38192. * * facetNormals : optional array of facet normals (vector3)
  38193. * * facetPositions : optional array of facet positions (vector3)
  38194. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38195. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38196. * * bInfo : optional bounding info, required for facetPartitioning computation
  38197. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38198. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38199. * * useRightHandedSystem: optional boolean to for right handed system computation
  38200. * * depthSort : optional boolean to enable the facet depth sort computation
  38201. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38202. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38203. */
  38204. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38205. // temporary scalar variables
  38206. var index = 0; // facet index
  38207. var p1p2x = 0.0; // p1p2 vector x coordinate
  38208. var p1p2y = 0.0; // p1p2 vector y coordinate
  38209. var p1p2z = 0.0; // p1p2 vector z coordinate
  38210. var p3p2x = 0.0; // p3p2 vector x coordinate
  38211. var p3p2y = 0.0; // p3p2 vector y coordinate
  38212. var p3p2z = 0.0; // p3p2 vector z coordinate
  38213. var faceNormalx = 0.0; // facet normal x coordinate
  38214. var faceNormaly = 0.0; // facet normal y coordinate
  38215. var faceNormalz = 0.0; // facet normal z coordinate
  38216. var length = 0.0; // facet normal length before normalization
  38217. var v1x = 0; // vector1 x index in the positions array
  38218. var v1y = 0; // vector1 y index in the positions array
  38219. var v1z = 0; // vector1 z index in the positions array
  38220. var v2x = 0; // vector2 x index in the positions array
  38221. var v2y = 0; // vector2 y index in the positions array
  38222. var v2z = 0; // vector2 z index in the positions array
  38223. var v3x = 0; // vector3 x index in the positions array
  38224. var v3y = 0; // vector3 y index in the positions array
  38225. var v3z = 0; // vector3 z index in the positions array
  38226. var computeFacetNormals = false;
  38227. var computeFacetPositions = false;
  38228. var computeFacetPartitioning = false;
  38229. var computeDepthSort = false;
  38230. var faceNormalSign = 1;
  38231. var ratio = 0;
  38232. var distanceTo = null;
  38233. if (options) {
  38234. computeFacetNormals = (options.facetNormals) ? true : false;
  38235. computeFacetPositions = (options.facetPositions) ? true : false;
  38236. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38237. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38238. ratio = options.ratio || 0;
  38239. computeDepthSort = (options.depthSort) ? true : false;
  38240. distanceTo = (options.distanceTo);
  38241. if (computeDepthSort) {
  38242. if (distanceTo === undefined) {
  38243. distanceTo = BABYLON.Vector3.Zero();
  38244. }
  38245. var depthSortedFacets = options.depthSortedFacets;
  38246. }
  38247. }
  38248. // facetPartitioning reinit if needed
  38249. var xSubRatio = 0;
  38250. var ySubRatio = 0;
  38251. var zSubRatio = 0;
  38252. var subSq = 0;
  38253. if (computeFacetPartitioning && options && options.bbSize) {
  38254. var ox = 0; // X partitioning index for facet position
  38255. var oy = 0; // Y partinioning index for facet position
  38256. var oz = 0; // Z partinioning index for facet position
  38257. var b1x = 0; // X partitioning index for facet v1 vertex
  38258. var b1y = 0; // Y partitioning index for facet v1 vertex
  38259. var b1z = 0; // z partitioning index for facet v1 vertex
  38260. var b2x = 0; // X partitioning index for facet v2 vertex
  38261. var b2y = 0; // Y partitioning index for facet v2 vertex
  38262. var b2z = 0; // Z partitioning index for facet v2 vertex
  38263. var b3x = 0; // X partitioning index for facet v3 vertex
  38264. var b3y = 0; // Y partitioning index for facet v3 vertex
  38265. var b3z = 0; // Z partitioning index for facet v3 vertex
  38266. var block_idx_o = 0; // facet barycenter block index
  38267. var block_idx_v1 = 0; // v1 vertex block index
  38268. var block_idx_v2 = 0; // v2 vertex block index
  38269. var block_idx_v3 = 0; // v3 vertex block index
  38270. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38271. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38272. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38273. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38274. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38275. subSq = options.subDiv.max * options.subDiv.max;
  38276. options.facetPartitioning.length = 0;
  38277. }
  38278. // reset the normals
  38279. for (index = 0; index < positions.length; index++) {
  38280. normals[index] = 0.0;
  38281. }
  38282. // Loop : 1 indice triplet = 1 facet
  38283. var nbFaces = (indices.length / 3) | 0;
  38284. for (index = 0; index < nbFaces; index++) {
  38285. // get the indexes of the coordinates of each vertex of the facet
  38286. v1x = indices[index * 3] * 3;
  38287. v1y = v1x + 1;
  38288. v1z = v1x + 2;
  38289. v2x = indices[index * 3 + 1] * 3;
  38290. v2y = v2x + 1;
  38291. v2z = v2x + 2;
  38292. v3x = indices[index * 3 + 2] * 3;
  38293. v3y = v3x + 1;
  38294. v3z = v3x + 2;
  38295. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38296. p1p2y = positions[v1y] - positions[v2y];
  38297. p1p2z = positions[v1z] - positions[v2z];
  38298. p3p2x = positions[v3x] - positions[v2x];
  38299. p3p2y = positions[v3y] - positions[v2y];
  38300. p3p2z = positions[v3z] - positions[v2z];
  38301. // compute the face normal with the cross product
  38302. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38303. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38304. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38305. // normalize this normal and store it in the array facetData
  38306. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38307. length = (length === 0) ? 1.0 : length;
  38308. faceNormalx /= length;
  38309. faceNormaly /= length;
  38310. faceNormalz /= length;
  38311. if (computeFacetNormals && options) {
  38312. options.facetNormals[index].x = faceNormalx;
  38313. options.facetNormals[index].y = faceNormaly;
  38314. options.facetNormals[index].z = faceNormalz;
  38315. }
  38316. if (computeFacetPositions && options) {
  38317. // compute and the facet barycenter coordinates in the array facetPositions
  38318. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38319. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38320. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38321. }
  38322. if (computeFacetPartitioning && options) {
  38323. // store the facet indexes in arrays in the main facetPartitioning array :
  38324. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38325. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38326. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38327. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38328. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38329. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38330. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38331. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38332. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38333. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38334. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38335. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38336. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38337. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38338. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38339. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38340. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38341. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38342. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38343. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38344. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38345. // push each facet index in each block containing the vertex
  38346. options.facetPartitioning[block_idx_v1].push(index);
  38347. if (block_idx_v2 != block_idx_v1) {
  38348. options.facetPartitioning[block_idx_v2].push(index);
  38349. }
  38350. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38351. options.facetPartitioning[block_idx_v3].push(index);
  38352. }
  38353. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38354. options.facetPartitioning[block_idx_o].push(index);
  38355. }
  38356. }
  38357. if (computeDepthSort && options && options.facetPositions) {
  38358. var dsf = depthSortedFacets[index];
  38359. dsf.ind = index * 3;
  38360. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38361. }
  38362. // compute the normals anyway
  38363. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38364. normals[v1y] += faceNormaly;
  38365. normals[v1z] += faceNormalz;
  38366. normals[v2x] += faceNormalx;
  38367. normals[v2y] += faceNormaly;
  38368. normals[v2z] += faceNormalz;
  38369. normals[v3x] += faceNormalx;
  38370. normals[v3y] += faceNormaly;
  38371. normals[v3z] += faceNormalz;
  38372. }
  38373. // last normalization of each normal
  38374. for (index = 0; index < normals.length / 3; index++) {
  38375. faceNormalx = normals[index * 3];
  38376. faceNormaly = normals[index * 3 + 1];
  38377. faceNormalz = normals[index * 3 + 2];
  38378. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38379. length = (length === 0) ? 1.0 : length;
  38380. faceNormalx /= length;
  38381. faceNormaly /= length;
  38382. faceNormalz /= length;
  38383. normals[index * 3] = faceNormalx;
  38384. normals[index * 3 + 1] = faceNormaly;
  38385. normals[index * 3 + 2] = faceNormalz;
  38386. }
  38387. };
  38388. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38389. var li = indices.length;
  38390. var ln = normals.length;
  38391. var i;
  38392. var n;
  38393. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38394. switch (sideOrientation) {
  38395. case BABYLON.Mesh.FRONTSIDE:
  38396. // nothing changed
  38397. break;
  38398. case BABYLON.Mesh.BACKSIDE:
  38399. var tmp;
  38400. // indices
  38401. for (i = 0; i < li; i += 3) {
  38402. tmp = indices[i];
  38403. indices[i] = indices[i + 2];
  38404. indices[i + 2] = tmp;
  38405. }
  38406. // normals
  38407. for (n = 0; n < ln; n++) {
  38408. normals[n] = -normals[n];
  38409. }
  38410. break;
  38411. case BABYLON.Mesh.DOUBLESIDE:
  38412. // positions
  38413. var lp = positions.length;
  38414. var l = lp / 3;
  38415. for (var p = 0; p < lp; p++) {
  38416. positions[lp + p] = positions[p];
  38417. }
  38418. // indices
  38419. for (i = 0; i < li; i += 3) {
  38420. indices[i + li] = indices[i + 2] + l;
  38421. indices[i + 1 + li] = indices[i + 1] + l;
  38422. indices[i + 2 + li] = indices[i] + l;
  38423. }
  38424. // normals
  38425. for (n = 0; n < ln; n++) {
  38426. normals[ln + n] = -normals[n];
  38427. }
  38428. // uvs
  38429. var lu = uvs.length;
  38430. var u = 0;
  38431. for (u = 0; u < lu; u++) {
  38432. uvs[u + lu] = uvs[u];
  38433. }
  38434. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38435. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38436. u = 0;
  38437. for (i = 0; i < lu / 2; i++) {
  38438. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38439. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38440. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38441. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38442. u += 2;
  38443. }
  38444. break;
  38445. }
  38446. };
  38447. /**
  38448. * Applies VertexData created from the imported parameters to the geometry
  38449. * @param parsedVertexData the parsed data from an imported file
  38450. * @param geometry the geometry to apply the VertexData to
  38451. */
  38452. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38453. var vertexData = new VertexData();
  38454. // positions
  38455. var positions = parsedVertexData.positions;
  38456. if (positions) {
  38457. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38458. }
  38459. // normals
  38460. var normals = parsedVertexData.normals;
  38461. if (normals) {
  38462. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38463. }
  38464. // tangents
  38465. var tangents = parsedVertexData.tangents;
  38466. if (tangents) {
  38467. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38468. }
  38469. // uvs
  38470. var uvs = parsedVertexData.uvs;
  38471. if (uvs) {
  38472. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38473. }
  38474. // uv2s
  38475. var uv2s = parsedVertexData.uv2s;
  38476. if (uv2s) {
  38477. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38478. }
  38479. // uv3s
  38480. var uv3s = parsedVertexData.uv3s;
  38481. if (uv3s) {
  38482. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38483. }
  38484. // uv4s
  38485. var uv4s = parsedVertexData.uv4s;
  38486. if (uv4s) {
  38487. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38488. }
  38489. // uv5s
  38490. var uv5s = parsedVertexData.uv5s;
  38491. if (uv5s) {
  38492. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38493. }
  38494. // uv6s
  38495. var uv6s = parsedVertexData.uv6s;
  38496. if (uv6s) {
  38497. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38498. }
  38499. // colors
  38500. var colors = parsedVertexData.colors;
  38501. if (colors) {
  38502. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38503. }
  38504. // matricesIndices
  38505. var matricesIndices = parsedVertexData.matricesIndices;
  38506. if (matricesIndices) {
  38507. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38508. }
  38509. // matricesWeights
  38510. var matricesWeights = parsedVertexData.matricesWeights;
  38511. if (matricesWeights) {
  38512. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38513. }
  38514. // indices
  38515. var indices = parsedVertexData.indices;
  38516. if (indices) {
  38517. vertexData.indices = indices;
  38518. }
  38519. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38520. };
  38521. return VertexData;
  38522. }());
  38523. BABYLON.VertexData = VertexData;
  38524. })(BABYLON || (BABYLON = {}));
  38525. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38526. var BABYLON;
  38527. (function (BABYLON) {
  38528. /**
  38529. * Class used to store geometry data (vertex buffers + index buffer)
  38530. */
  38531. var Geometry = /** @class */ (function () {
  38532. /**
  38533. * Creates a new geometry
  38534. * @param id defines the unique ID
  38535. * @param scene defines the hosting scene
  38536. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38537. * @param updatable defines if geometry must be updatable (false by default)
  38538. * @param mesh defines the mesh that will be associated with the geometry
  38539. */
  38540. function Geometry(id, scene, vertexData, updatable, mesh) {
  38541. if (updatable === void 0) { updatable = false; }
  38542. if (mesh === void 0) { mesh = null; }
  38543. /**
  38544. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38545. */
  38546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38547. this._totalVertices = 0;
  38548. this._isDisposed = false;
  38549. this._indexBufferIsUpdatable = false;
  38550. this.id = id;
  38551. this._engine = scene.getEngine();
  38552. this._meshes = [];
  38553. this._scene = scene;
  38554. //Init vertex buffer cache
  38555. this._vertexBuffers = {};
  38556. this._indices = [];
  38557. this._updatable = updatable;
  38558. // vertexData
  38559. if (vertexData) {
  38560. this.setAllVerticesData(vertexData, updatable);
  38561. }
  38562. else {
  38563. this._totalVertices = 0;
  38564. this._indices = [];
  38565. }
  38566. if (this._engine.getCaps().vertexArrayObject) {
  38567. this._vertexArrayObjects = {};
  38568. }
  38569. // applyToMesh
  38570. if (mesh) {
  38571. if (mesh.getClassName() === "LinesMesh") {
  38572. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38573. this._updateExtend();
  38574. }
  38575. this.applyToMesh(mesh);
  38576. mesh.computeWorldMatrix(true);
  38577. }
  38578. }
  38579. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38580. /**
  38581. * 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
  38582. */
  38583. get: function () {
  38584. return this._boundingBias;
  38585. },
  38586. /**
  38587. * 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
  38588. */
  38589. set: function (value) {
  38590. if (this._boundingBias && this._boundingBias.equals(value)) {
  38591. return;
  38592. }
  38593. this._boundingBias = value.clone();
  38594. this._updateBoundingInfo(true, null);
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. /**
  38600. * Static function used to attach a new empty geometry to a mesh
  38601. * @param mesh defines the mesh to attach the geometry to
  38602. * @returns the new {BABYLON.Geometry}
  38603. */
  38604. Geometry.CreateGeometryForMesh = function (mesh) {
  38605. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38606. geometry.applyToMesh(mesh);
  38607. return geometry;
  38608. };
  38609. Object.defineProperty(Geometry.prototype, "extend", {
  38610. /**
  38611. * Gets the current extend of the geometry
  38612. */
  38613. get: function () {
  38614. return this._extend;
  38615. },
  38616. enumerable: true,
  38617. configurable: true
  38618. });
  38619. /**
  38620. * Gets the hosting scene
  38621. * @returns the hosting {BABYLON.Scene}
  38622. */
  38623. Geometry.prototype.getScene = function () {
  38624. return this._scene;
  38625. };
  38626. /**
  38627. * Gets the hosting engine
  38628. * @returns the hosting {BABYLON.Engine}
  38629. */
  38630. Geometry.prototype.getEngine = function () {
  38631. return this._engine;
  38632. };
  38633. /**
  38634. * Defines if the geometry is ready to use
  38635. * @returns true if the geometry is ready to be used
  38636. */
  38637. Geometry.prototype.isReady = function () {
  38638. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38639. };
  38640. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38641. /**
  38642. * Gets a value indicating that the geometry should not be serialized
  38643. */
  38644. get: function () {
  38645. for (var index = 0; index < this._meshes.length; index++) {
  38646. if (!this._meshes[index].doNotSerialize) {
  38647. return false;
  38648. }
  38649. }
  38650. return true;
  38651. },
  38652. enumerable: true,
  38653. configurable: true
  38654. });
  38655. /** @hidden */
  38656. Geometry.prototype._rebuild = function () {
  38657. if (this._vertexArrayObjects) {
  38658. this._vertexArrayObjects = {};
  38659. }
  38660. // Index buffer
  38661. if (this._meshes.length !== 0 && this._indices) {
  38662. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38663. }
  38664. // Vertex buffers
  38665. for (var key in this._vertexBuffers) {
  38666. var vertexBuffer = this._vertexBuffers[key];
  38667. vertexBuffer._rebuild();
  38668. }
  38669. };
  38670. /**
  38671. * Affects all geometry data in one call
  38672. * @param vertexData defines the geometry data
  38673. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38674. */
  38675. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38676. vertexData.applyToGeometry(this, updatable);
  38677. this.notifyUpdate();
  38678. };
  38679. /**
  38680. * Set specific vertex data
  38681. * @param kind defines the data kind (Position, normal, etc...)
  38682. * @param data defines the vertex data to use
  38683. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38684. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38685. */
  38686. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38687. if (updatable === void 0) { updatable = false; }
  38688. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38689. this.setVerticesBuffer(buffer);
  38690. };
  38691. /**
  38692. * Removes a specific vertex data
  38693. * @param kind defines the data kind (Position, normal, etc...)
  38694. */
  38695. Geometry.prototype.removeVerticesData = function (kind) {
  38696. if (this._vertexBuffers[kind]) {
  38697. this._vertexBuffers[kind].dispose();
  38698. delete this._vertexBuffers[kind];
  38699. }
  38700. };
  38701. /**
  38702. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38703. * @param buffer defines the vertex buffer to use
  38704. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38705. */
  38706. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38707. if (totalVertices === void 0) { totalVertices = null; }
  38708. var kind = buffer.getKind();
  38709. if (this._vertexBuffers[kind]) {
  38710. this._vertexBuffers[kind].dispose();
  38711. }
  38712. this._vertexBuffers[kind] = buffer;
  38713. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38714. var data = buffer.getData();
  38715. if (totalVertices != null) {
  38716. this._totalVertices = totalVertices;
  38717. }
  38718. else {
  38719. if (data != null) {
  38720. this._totalVertices = data.length / (buffer.byteStride / 4);
  38721. }
  38722. }
  38723. this._updateExtend(data);
  38724. this._resetPointsArrayCache();
  38725. var meshes = this._meshes;
  38726. var numOfMeshes = meshes.length;
  38727. for (var index = 0; index < numOfMeshes; index++) {
  38728. var mesh = meshes[index];
  38729. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38730. mesh._createGlobalSubMesh(false);
  38731. mesh.computeWorldMatrix(true);
  38732. }
  38733. }
  38734. this.notifyUpdate(kind);
  38735. if (this._vertexArrayObjects) {
  38736. this._disposeVertexArrayObjects();
  38737. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38738. }
  38739. };
  38740. /**
  38741. * Update a specific vertex buffer
  38742. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38743. * It will do nothing if the buffer is not updatable
  38744. * @param kind defines the data kind (Position, normal, etc...)
  38745. * @param data defines the data to use
  38746. * @param offset defines the offset in the target buffer where to store the data
  38747. * @param useBytes set to true if the offset is in bytes
  38748. */
  38749. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38750. if (useBytes === void 0) { useBytes = false; }
  38751. var vertexBuffer = this.getVertexBuffer(kind);
  38752. if (!vertexBuffer) {
  38753. return;
  38754. }
  38755. vertexBuffer.updateDirectly(data, offset, useBytes);
  38756. this.notifyUpdate(kind);
  38757. };
  38758. /**
  38759. * Update a specific vertex buffer
  38760. * This function will create a new buffer if the current one is not updatable
  38761. * @param kind defines the data kind (Position, normal, etc...)
  38762. * @param data defines the data to use
  38763. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38764. */
  38765. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38766. if (updateExtends === void 0) { updateExtends = false; }
  38767. var vertexBuffer = this.getVertexBuffer(kind);
  38768. if (!vertexBuffer) {
  38769. return;
  38770. }
  38771. vertexBuffer.update(data);
  38772. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38773. this._updateBoundingInfo(updateExtends, data);
  38774. }
  38775. this.notifyUpdate(kind);
  38776. };
  38777. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38778. if (updateExtends) {
  38779. this._updateExtend(data);
  38780. }
  38781. var meshes = this._meshes;
  38782. var numOfMeshes = meshes.length;
  38783. this._resetPointsArrayCache();
  38784. for (var index = 0; index < numOfMeshes; index++) {
  38785. var mesh = meshes[index];
  38786. if (updateExtends) {
  38787. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38788. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38789. var subMesh = mesh.subMeshes[subIndex];
  38790. subMesh.refreshBoundingInfo();
  38791. }
  38792. }
  38793. }
  38794. };
  38795. /** @hidden */
  38796. Geometry.prototype._bind = function (effect, indexToBind) {
  38797. if (!effect) {
  38798. return;
  38799. }
  38800. if (indexToBind === undefined) {
  38801. indexToBind = this._indexBuffer;
  38802. }
  38803. var vbs = this.getVertexBuffers();
  38804. if (!vbs) {
  38805. return;
  38806. }
  38807. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38808. this._engine.bindBuffers(vbs, indexToBind, effect);
  38809. return;
  38810. }
  38811. // Using VAO
  38812. if (!this._vertexArrayObjects[effect.key]) {
  38813. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38814. }
  38815. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38816. };
  38817. /**
  38818. * Gets total number of vertices
  38819. * @returns the total number of vertices
  38820. */
  38821. Geometry.prototype.getTotalVertices = function () {
  38822. if (!this.isReady()) {
  38823. return 0;
  38824. }
  38825. return this._totalVertices;
  38826. };
  38827. /**
  38828. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38829. * @param kind defines the data kind (Position, normal, etc...)
  38830. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38831. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38832. * @returns a float array containing vertex data
  38833. */
  38834. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38835. var vertexBuffer = this.getVertexBuffer(kind);
  38836. if (!vertexBuffer) {
  38837. return null;
  38838. }
  38839. var data = vertexBuffer.getData();
  38840. if (!data) {
  38841. return null;
  38842. }
  38843. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38844. var count = this._totalVertices * vertexBuffer.getSize();
  38845. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38846. var copy_1 = new Array(count);
  38847. vertexBuffer.forEach(count, function (value, index) {
  38848. copy_1[index] = value;
  38849. });
  38850. return copy_1;
  38851. }
  38852. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38853. if (data instanceof Array) {
  38854. var offset = vertexBuffer.byteOffset / 4;
  38855. return BABYLON.Tools.Slice(data, offset, offset + count);
  38856. }
  38857. else if (data instanceof ArrayBuffer) {
  38858. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38859. }
  38860. else {
  38861. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38862. }
  38863. }
  38864. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38865. return BABYLON.Tools.Slice(data);
  38866. }
  38867. return data;
  38868. };
  38869. /**
  38870. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38871. * @param kind defines the data kind (Position, normal, etc...)
  38872. * @returns true if the vertex buffer with the specified kind is updatable
  38873. */
  38874. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38875. var vb = this._vertexBuffers[kind];
  38876. if (!vb) {
  38877. return false;
  38878. }
  38879. return vb.isUpdatable();
  38880. };
  38881. /**
  38882. * Gets a specific vertex buffer
  38883. * @param kind defines the data kind (Position, normal, etc...)
  38884. * @returns a {BABYLON.VertexBuffer}
  38885. */
  38886. Geometry.prototype.getVertexBuffer = function (kind) {
  38887. if (!this.isReady()) {
  38888. return null;
  38889. }
  38890. return this._vertexBuffers[kind];
  38891. };
  38892. /**
  38893. * Returns all vertex buffers
  38894. * @return an object holding all vertex buffers indexed by kind
  38895. */
  38896. Geometry.prototype.getVertexBuffers = function () {
  38897. if (!this.isReady()) {
  38898. return null;
  38899. }
  38900. return this._vertexBuffers;
  38901. };
  38902. /**
  38903. * Gets a boolean indicating if specific vertex buffer is present
  38904. * @param kind defines the data kind (Position, normal, etc...)
  38905. * @returns true if data is present
  38906. */
  38907. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38908. if (!this._vertexBuffers) {
  38909. if (this._delayInfo) {
  38910. return this._delayInfo.indexOf(kind) !== -1;
  38911. }
  38912. return false;
  38913. }
  38914. return this._vertexBuffers[kind] !== undefined;
  38915. };
  38916. /**
  38917. * Gets a list of all attached data kinds (Position, normal, etc...)
  38918. * @returns a list of string containing all kinds
  38919. */
  38920. Geometry.prototype.getVerticesDataKinds = function () {
  38921. var result = [];
  38922. var kind;
  38923. if (!this._vertexBuffers && this._delayInfo) {
  38924. for (kind in this._delayInfo) {
  38925. result.push(kind);
  38926. }
  38927. }
  38928. else {
  38929. for (kind in this._vertexBuffers) {
  38930. result.push(kind);
  38931. }
  38932. }
  38933. return result;
  38934. };
  38935. /**
  38936. * Update index buffer
  38937. * @param indices defines the indices to store in the index buffer
  38938. * @param offset defines the offset in the target buffer where to store the data
  38939. */
  38940. Geometry.prototype.updateIndices = function (indices, offset) {
  38941. if (!this._indexBuffer) {
  38942. return;
  38943. }
  38944. if (!this._indexBufferIsUpdatable) {
  38945. this.setIndices(indices, null, true);
  38946. }
  38947. else {
  38948. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38949. }
  38950. };
  38951. /**
  38952. * Creates a new index buffer
  38953. * @param indices defines the indices to store in the index buffer
  38954. * @param totalVertices defines the total number of vertices (could be null)
  38955. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38956. */
  38957. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38958. if (totalVertices === void 0) { totalVertices = null; }
  38959. if (updatable === void 0) { updatable = false; }
  38960. if (this._indexBuffer) {
  38961. this._engine._releaseBuffer(this._indexBuffer);
  38962. }
  38963. this._disposeVertexArrayObjects();
  38964. this._indices = indices;
  38965. this._indexBufferIsUpdatable = updatable;
  38966. if (this._meshes.length !== 0 && this._indices) {
  38967. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38968. }
  38969. if (totalVertices != undefined) { // including null and undefined
  38970. this._totalVertices = totalVertices;
  38971. }
  38972. var meshes = this._meshes;
  38973. var numOfMeshes = meshes.length;
  38974. for (var index = 0; index < numOfMeshes; index++) {
  38975. meshes[index]._createGlobalSubMesh(true);
  38976. }
  38977. this.notifyUpdate();
  38978. };
  38979. /**
  38980. * Return the total number of indices
  38981. * @returns the total number of indices
  38982. */
  38983. Geometry.prototype.getTotalIndices = function () {
  38984. if (!this.isReady()) {
  38985. return 0;
  38986. }
  38987. return this._indices.length;
  38988. };
  38989. /**
  38990. * Gets the index buffer array
  38991. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38992. * @returns the index buffer array
  38993. */
  38994. Geometry.prototype.getIndices = function (copyWhenShared) {
  38995. if (!this.isReady()) {
  38996. return null;
  38997. }
  38998. var orig = this._indices;
  38999. if (!copyWhenShared || this._meshes.length === 1) {
  39000. return orig;
  39001. }
  39002. else {
  39003. var len = orig.length;
  39004. var copy = [];
  39005. for (var i = 0; i < len; i++) {
  39006. copy.push(orig[i]);
  39007. }
  39008. return copy;
  39009. }
  39010. };
  39011. /**
  39012. * Gets the index buffer
  39013. * @return the index buffer
  39014. */
  39015. Geometry.prototype.getIndexBuffer = function () {
  39016. if (!this.isReady()) {
  39017. return null;
  39018. }
  39019. return this._indexBuffer;
  39020. };
  39021. /** @hidden */
  39022. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39023. if (effect === void 0) { effect = null; }
  39024. if (!effect || !this._vertexArrayObjects) {
  39025. return;
  39026. }
  39027. if (this._vertexArrayObjects[effect.key]) {
  39028. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39029. delete this._vertexArrayObjects[effect.key];
  39030. }
  39031. };
  39032. /**
  39033. * Release the associated resources for a specific mesh
  39034. * @param mesh defines the source mesh
  39035. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39036. */
  39037. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39038. var meshes = this._meshes;
  39039. var index = meshes.indexOf(mesh);
  39040. if (index === -1) {
  39041. return;
  39042. }
  39043. meshes.splice(index, 1);
  39044. mesh._geometry = null;
  39045. if (meshes.length === 0 && shouldDispose) {
  39046. this.dispose();
  39047. }
  39048. };
  39049. /**
  39050. * Apply current geometry to a given mesh
  39051. * @param mesh defines the mesh to apply geometry to
  39052. */
  39053. Geometry.prototype.applyToMesh = function (mesh) {
  39054. if (mesh._geometry === this) {
  39055. return;
  39056. }
  39057. var previousGeometry = mesh._geometry;
  39058. if (previousGeometry) {
  39059. previousGeometry.releaseForMesh(mesh);
  39060. }
  39061. var meshes = this._meshes;
  39062. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39063. mesh._geometry = this;
  39064. this._scene.pushGeometry(this);
  39065. meshes.push(mesh);
  39066. if (this.isReady()) {
  39067. this._applyToMesh(mesh);
  39068. }
  39069. else {
  39070. mesh._boundingInfo = this._boundingInfo;
  39071. }
  39072. };
  39073. Geometry.prototype._updateExtend = function (data) {
  39074. if (data === void 0) { data = null; }
  39075. if (!data) {
  39076. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39077. }
  39078. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39079. };
  39080. Geometry.prototype._applyToMesh = function (mesh) {
  39081. var numOfMeshes = this._meshes.length;
  39082. // vertexBuffers
  39083. for (var kind in this._vertexBuffers) {
  39084. if (numOfMeshes === 1) {
  39085. this._vertexBuffers[kind].create();
  39086. }
  39087. var buffer = this._vertexBuffers[kind].getBuffer();
  39088. if (buffer)
  39089. buffer.references = numOfMeshes;
  39090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39091. if (!this._extend) {
  39092. this._updateExtend();
  39093. }
  39094. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39095. mesh._createGlobalSubMesh(false);
  39096. //bounding info was just created again, world matrix should be applied again.
  39097. mesh._updateBoundingInfo();
  39098. }
  39099. }
  39100. // indexBuffer
  39101. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39102. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39103. }
  39104. if (this._indexBuffer) {
  39105. this._indexBuffer.references = numOfMeshes;
  39106. }
  39107. };
  39108. Geometry.prototype.notifyUpdate = function (kind) {
  39109. if (this.onGeometryUpdated) {
  39110. this.onGeometryUpdated(this, kind);
  39111. }
  39112. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39113. var mesh = _a[_i];
  39114. mesh._markSubMeshesAsAttributesDirty();
  39115. }
  39116. };
  39117. /**
  39118. * Load the geometry if it was flagged as delay loaded
  39119. * @param scene defines the hosting scene
  39120. * @param onLoaded defines a callback called when the geometry is loaded
  39121. */
  39122. Geometry.prototype.load = function (scene, onLoaded) {
  39123. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39124. return;
  39125. }
  39126. if (this.isReady()) {
  39127. if (onLoaded) {
  39128. onLoaded();
  39129. }
  39130. return;
  39131. }
  39132. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39133. this._queueLoad(scene, onLoaded);
  39134. };
  39135. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39136. var _this = this;
  39137. if (!this.delayLoadingFile) {
  39138. return;
  39139. }
  39140. scene._addPendingData(this);
  39141. scene._loadFile(this.delayLoadingFile, function (data) {
  39142. if (!_this._delayLoadingFunction) {
  39143. return;
  39144. }
  39145. _this._delayLoadingFunction(JSON.parse(data), _this);
  39146. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39147. _this._delayInfo = [];
  39148. scene._removePendingData(_this);
  39149. var meshes = _this._meshes;
  39150. var numOfMeshes = meshes.length;
  39151. for (var index = 0; index < numOfMeshes; index++) {
  39152. _this._applyToMesh(meshes[index]);
  39153. }
  39154. if (onLoaded) {
  39155. onLoaded();
  39156. }
  39157. }, undefined, true);
  39158. };
  39159. /**
  39160. * Invert the geometry to move from a right handed system to a left handed one.
  39161. */
  39162. Geometry.prototype.toLeftHanded = function () {
  39163. // Flip faces
  39164. var tIndices = this.getIndices(false);
  39165. if (tIndices != null && tIndices.length > 0) {
  39166. for (var i = 0; i < tIndices.length; i += 3) {
  39167. var tTemp = tIndices[i + 0];
  39168. tIndices[i + 0] = tIndices[i + 2];
  39169. tIndices[i + 2] = tTemp;
  39170. }
  39171. this.setIndices(tIndices);
  39172. }
  39173. // Negate position.z
  39174. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39175. if (tPositions != null && tPositions.length > 0) {
  39176. for (var i = 0; i < tPositions.length; i += 3) {
  39177. tPositions[i + 2] = -tPositions[i + 2];
  39178. }
  39179. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39180. }
  39181. // Negate normal.z
  39182. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39183. if (tNormals != null && tNormals.length > 0) {
  39184. for (var i = 0; i < tNormals.length; i += 3) {
  39185. tNormals[i + 2] = -tNormals[i + 2];
  39186. }
  39187. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39188. }
  39189. };
  39190. // Cache
  39191. /** @hidden */
  39192. Geometry.prototype._resetPointsArrayCache = function () {
  39193. this._positions = null;
  39194. };
  39195. /** @hidden */
  39196. Geometry.prototype._generatePointsArray = function () {
  39197. if (this._positions)
  39198. return true;
  39199. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39200. if (!data || data.length === 0) {
  39201. return false;
  39202. }
  39203. this._positions = [];
  39204. for (var index = 0; index < data.length; index += 3) {
  39205. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39206. }
  39207. return true;
  39208. };
  39209. /**
  39210. * Gets a value indicating if the geometry is disposed
  39211. * @returns true if the geometry was disposed
  39212. */
  39213. Geometry.prototype.isDisposed = function () {
  39214. return this._isDisposed;
  39215. };
  39216. Geometry.prototype._disposeVertexArrayObjects = function () {
  39217. if (this._vertexArrayObjects) {
  39218. for (var kind in this._vertexArrayObjects) {
  39219. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39220. }
  39221. this._vertexArrayObjects = {};
  39222. }
  39223. };
  39224. /**
  39225. * Free all associated resources
  39226. */
  39227. Geometry.prototype.dispose = function () {
  39228. var meshes = this._meshes;
  39229. var numOfMeshes = meshes.length;
  39230. var index;
  39231. for (index = 0; index < numOfMeshes; index++) {
  39232. this.releaseForMesh(meshes[index]);
  39233. }
  39234. this._meshes = [];
  39235. this._disposeVertexArrayObjects();
  39236. for (var kind in this._vertexBuffers) {
  39237. this._vertexBuffers[kind].dispose();
  39238. }
  39239. this._vertexBuffers = {};
  39240. this._totalVertices = 0;
  39241. if (this._indexBuffer) {
  39242. this._engine._releaseBuffer(this._indexBuffer);
  39243. }
  39244. this._indexBuffer = null;
  39245. this._indices = [];
  39246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39247. this.delayLoadingFile = null;
  39248. this._delayLoadingFunction = null;
  39249. this._delayInfo = [];
  39250. this._boundingInfo = null;
  39251. this._scene.removeGeometry(this);
  39252. this._isDisposed = true;
  39253. };
  39254. /**
  39255. * Clone the current geometry into a new geometry
  39256. * @param id defines the unique ID of the new geometry
  39257. * @returns a new geometry object
  39258. */
  39259. Geometry.prototype.copy = function (id) {
  39260. var vertexData = new BABYLON.VertexData();
  39261. vertexData.indices = [];
  39262. var indices = this.getIndices();
  39263. if (indices) {
  39264. for (var index = 0; index < indices.length; index++) {
  39265. vertexData.indices.push(indices[index]);
  39266. }
  39267. }
  39268. var updatable = false;
  39269. var stopChecking = false;
  39270. var kind;
  39271. for (kind in this._vertexBuffers) {
  39272. // using slice() to make a copy of the array and not just reference it
  39273. var data = this.getVerticesData(kind);
  39274. if (data instanceof Float32Array) {
  39275. vertexData.set(new Float32Array(data), kind);
  39276. }
  39277. else {
  39278. vertexData.set(data.slice(0), kind);
  39279. }
  39280. if (!stopChecking) {
  39281. var vb = this.getVertexBuffer(kind);
  39282. if (vb) {
  39283. updatable = vb.isUpdatable();
  39284. stopChecking = !updatable;
  39285. }
  39286. }
  39287. }
  39288. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39289. geometry.delayLoadState = this.delayLoadState;
  39290. geometry.delayLoadingFile = this.delayLoadingFile;
  39291. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39292. for (kind in this._delayInfo) {
  39293. geometry._delayInfo = geometry._delayInfo || [];
  39294. geometry._delayInfo.push(kind);
  39295. }
  39296. // Bounding info
  39297. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39298. return geometry;
  39299. };
  39300. /**
  39301. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39302. * @return a JSON representation of the current geometry data (without the vertices data)
  39303. */
  39304. Geometry.prototype.serialize = function () {
  39305. var serializationObject = {};
  39306. serializationObject.id = this.id;
  39307. serializationObject.updatable = this._updatable;
  39308. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39309. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39310. }
  39311. return serializationObject;
  39312. };
  39313. Geometry.prototype.toNumberArray = function (origin) {
  39314. if (Array.isArray(origin)) {
  39315. return origin;
  39316. }
  39317. else {
  39318. return Array.prototype.slice.call(origin);
  39319. }
  39320. };
  39321. /**
  39322. * Serialize all vertices data into a JSON oject
  39323. * @returns a JSON representation of the current geometry data
  39324. */
  39325. Geometry.prototype.serializeVerticeData = function () {
  39326. var serializationObject = this.serialize();
  39327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39328. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39329. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39330. serializationObject.positions._updatable = true;
  39331. }
  39332. }
  39333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39334. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39335. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39336. serializationObject.normals._updatable = true;
  39337. }
  39338. }
  39339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39340. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39341. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39342. serializationObject.tangets._updatable = true;
  39343. }
  39344. }
  39345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39346. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39347. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39348. serializationObject.uvs._updatable = true;
  39349. }
  39350. }
  39351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39352. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39353. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39354. serializationObject.uv2s._updatable = true;
  39355. }
  39356. }
  39357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39358. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39359. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39360. serializationObject.uv3s._updatable = true;
  39361. }
  39362. }
  39363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39364. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39365. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39366. serializationObject.uv4s._updatable = true;
  39367. }
  39368. }
  39369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39370. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39372. serializationObject.uv5s._updatable = true;
  39373. }
  39374. }
  39375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39376. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39378. serializationObject.uv6s._updatable = true;
  39379. }
  39380. }
  39381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39382. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39384. serializationObject.colors._updatable = true;
  39385. }
  39386. }
  39387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39388. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39389. serializationObject.matricesIndices._isExpanded = true;
  39390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39391. serializationObject.matricesIndices._updatable = true;
  39392. }
  39393. }
  39394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39395. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39397. serializationObject.matricesWeights._updatable = true;
  39398. }
  39399. }
  39400. serializationObject.indices = this.toNumberArray(this.getIndices());
  39401. return serializationObject;
  39402. };
  39403. // Statics
  39404. /**
  39405. * Extracts a clone of a mesh geometry
  39406. * @param mesh defines the source mesh
  39407. * @param id defines the unique ID of the new geometry object
  39408. * @returns the new geometry object
  39409. */
  39410. Geometry.ExtractFromMesh = function (mesh, id) {
  39411. var geometry = mesh._geometry;
  39412. if (!geometry) {
  39413. return null;
  39414. }
  39415. return geometry.copy(id);
  39416. };
  39417. /**
  39418. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39419. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39420. * Be aware Math.random() could cause collisions, but:
  39421. * "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"
  39422. * @returns a string containing a new GUID
  39423. */
  39424. Geometry.RandomId = function () {
  39425. return BABYLON.Tools.RandomId();
  39426. };
  39427. /** @hidden */
  39428. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39429. var scene = mesh.getScene();
  39430. // Geometry
  39431. var geometryId = parsedGeometry.geometryId;
  39432. if (geometryId) {
  39433. var geometry = scene.getGeometryByID(geometryId);
  39434. if (geometry) {
  39435. geometry.applyToMesh(mesh);
  39436. }
  39437. }
  39438. else if (parsedGeometry instanceof ArrayBuffer) {
  39439. var binaryInfo = mesh._binaryInfo;
  39440. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39441. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39442. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39443. }
  39444. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39445. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39446. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39447. }
  39448. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39449. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39451. }
  39452. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39453. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39455. }
  39456. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39457. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39459. }
  39460. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39461. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39463. }
  39464. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39465. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39466. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39467. }
  39468. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39469. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39471. }
  39472. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39473. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39474. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39475. }
  39476. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39477. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39478. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39479. }
  39480. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39481. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39482. var floatIndices = [];
  39483. for (var i = 0; i < matricesIndicesData.length; i++) {
  39484. var index = matricesIndicesData[i];
  39485. floatIndices.push(index & 0x000000FF);
  39486. floatIndices.push((index & 0x0000FF00) >> 8);
  39487. floatIndices.push((index & 0x00FF0000) >> 16);
  39488. floatIndices.push(index >> 24);
  39489. }
  39490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39491. }
  39492. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39493. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39495. }
  39496. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39497. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39498. mesh.setIndices(indicesData, null);
  39499. }
  39500. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39501. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39502. mesh.subMeshes = [];
  39503. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39504. var materialIndex = subMeshesData[(i * 5) + 0];
  39505. var verticesStart = subMeshesData[(i * 5) + 1];
  39506. var verticesCount = subMeshesData[(i * 5) + 2];
  39507. var indexStart = subMeshesData[(i * 5) + 3];
  39508. var indexCount = subMeshesData[(i * 5) + 4];
  39509. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39510. }
  39511. }
  39512. }
  39513. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39515. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39516. if (parsedGeometry.tangents) {
  39517. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39518. }
  39519. if (parsedGeometry.uvs) {
  39520. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39521. }
  39522. if (parsedGeometry.uvs2) {
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39524. }
  39525. if (parsedGeometry.uvs3) {
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39527. }
  39528. if (parsedGeometry.uvs4) {
  39529. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39530. }
  39531. if (parsedGeometry.uvs5) {
  39532. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39533. }
  39534. if (parsedGeometry.uvs6) {
  39535. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39536. }
  39537. if (parsedGeometry.colors) {
  39538. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39539. }
  39540. if (parsedGeometry.matricesIndices) {
  39541. if (!parsedGeometry.matricesIndices._isExpanded) {
  39542. var floatIndices = [];
  39543. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39544. var matricesIndex = parsedGeometry.matricesIndices[i];
  39545. floatIndices.push(matricesIndex & 0x000000FF);
  39546. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39547. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39548. floatIndices.push(matricesIndex >> 24);
  39549. }
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39551. }
  39552. else {
  39553. delete parsedGeometry.matricesIndices._isExpanded;
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39555. }
  39556. }
  39557. if (parsedGeometry.matricesIndicesExtra) {
  39558. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39559. var floatIndices = [];
  39560. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39561. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39562. floatIndices.push(matricesIndex & 0x000000FF);
  39563. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39564. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39565. floatIndices.push(matricesIndex >> 24);
  39566. }
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39568. }
  39569. else {
  39570. delete parsedGeometry.matricesIndices._isExpanded;
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39572. }
  39573. }
  39574. if (parsedGeometry.matricesWeights) {
  39575. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39577. }
  39578. if (parsedGeometry.matricesWeightsExtra) {
  39579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39580. }
  39581. mesh.setIndices(parsedGeometry.indices, null);
  39582. }
  39583. // SubMeshes
  39584. if (parsedGeometry.subMeshes) {
  39585. mesh.subMeshes = [];
  39586. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39587. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39588. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39589. }
  39590. }
  39591. // Flat shading
  39592. if (mesh._shouldGenerateFlatShading) {
  39593. mesh.convertToFlatShadedMesh();
  39594. delete mesh._shouldGenerateFlatShading;
  39595. }
  39596. // Update
  39597. mesh.computeWorldMatrix(true);
  39598. // Octree
  39599. var sceneOctree = scene.selectionOctree;
  39600. if (sceneOctree !== undefined && sceneOctree !== null) {
  39601. sceneOctree.addMesh(mesh);
  39602. }
  39603. };
  39604. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39605. var epsilon = 1e-3;
  39606. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39607. return;
  39608. }
  39609. var noInfluenceBoneIndex = 0.0;
  39610. if (parsedGeometry.skeletonId > -1) {
  39611. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39612. if (!skeleton) {
  39613. return;
  39614. }
  39615. noInfluenceBoneIndex = skeleton.bones.length;
  39616. }
  39617. else {
  39618. return;
  39619. }
  39620. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39621. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39622. var matricesWeights = parsedGeometry.matricesWeights;
  39623. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39624. var influencers = parsedGeometry.numBoneInfluencer;
  39625. var size = matricesWeights.length;
  39626. for (var i = 0; i < size; i += 4) {
  39627. var weight = 0.0;
  39628. var firstZeroWeight = -1;
  39629. for (var j = 0; j < 4; j++) {
  39630. var w = matricesWeights[i + j];
  39631. weight += w;
  39632. if (w < epsilon && firstZeroWeight < 0) {
  39633. firstZeroWeight = j;
  39634. }
  39635. }
  39636. if (matricesWeightsExtra) {
  39637. for (var j = 0; j < 4; j++) {
  39638. var w = matricesWeightsExtra[i + j];
  39639. weight += w;
  39640. if (w < epsilon && firstZeroWeight < 0) {
  39641. firstZeroWeight = j + 4;
  39642. }
  39643. }
  39644. }
  39645. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39646. firstZeroWeight = influencers - 1;
  39647. }
  39648. if (weight > epsilon) {
  39649. var mweight = 1.0 / weight;
  39650. for (var j = 0; j < 4; j++) {
  39651. matricesWeights[i + j] *= mweight;
  39652. }
  39653. if (matricesWeightsExtra) {
  39654. for (var j = 0; j < 4; j++) {
  39655. matricesWeightsExtra[i + j] *= mweight;
  39656. }
  39657. }
  39658. }
  39659. else {
  39660. if (firstZeroWeight >= 4) {
  39661. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39662. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39663. }
  39664. else {
  39665. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39666. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39667. }
  39668. }
  39669. }
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39671. if (parsedGeometry.matricesWeightsExtra) {
  39672. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39673. }
  39674. };
  39675. /**
  39676. * Create a new geometry from persisted data (Using .babylon file format)
  39677. * @param parsedVertexData defines the persisted data
  39678. * @param scene defines the hosting scene
  39679. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39680. * @returns the new geometry object
  39681. */
  39682. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39683. if (scene.getGeometryByID(parsedVertexData.id)) {
  39684. return null; // null since geometry could be something else than a box...
  39685. }
  39686. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39687. if (BABYLON.Tags) {
  39688. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39689. }
  39690. if (parsedVertexData.delayLoadingFile) {
  39691. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39692. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39693. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39694. geometry._delayInfo = [];
  39695. if (parsedVertexData.hasUVs) {
  39696. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39697. }
  39698. if (parsedVertexData.hasUVs2) {
  39699. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39700. }
  39701. if (parsedVertexData.hasUVs3) {
  39702. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39703. }
  39704. if (parsedVertexData.hasUVs4) {
  39705. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39706. }
  39707. if (parsedVertexData.hasUVs5) {
  39708. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39709. }
  39710. if (parsedVertexData.hasUVs6) {
  39711. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39712. }
  39713. if (parsedVertexData.hasColors) {
  39714. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39715. }
  39716. if (parsedVertexData.hasMatricesIndices) {
  39717. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39718. }
  39719. if (parsedVertexData.hasMatricesWeights) {
  39720. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39721. }
  39722. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39723. }
  39724. else {
  39725. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39726. }
  39727. scene.pushGeometry(geometry, true);
  39728. return geometry;
  39729. };
  39730. return Geometry;
  39731. }());
  39732. BABYLON.Geometry = Geometry;
  39733. // Primitives
  39734. /// Abstract class
  39735. /**
  39736. * Abstract class used to provide common services for all typed geometries
  39737. * @hidden
  39738. */
  39739. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39740. __extends(_PrimitiveGeometry, _super);
  39741. /**
  39742. * Creates a new typed geometry
  39743. * @param id defines the unique ID of the geometry
  39744. * @param scene defines the hosting scene
  39745. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39746. * @param mesh defines the hosting mesh (can be null)
  39747. */
  39748. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39749. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39750. if (mesh === void 0) { mesh = null; }
  39751. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39752. _this._canBeRegenerated = _canBeRegenerated;
  39753. _this._beingRegenerated = true;
  39754. _this.regenerate();
  39755. _this._beingRegenerated = false;
  39756. return _this;
  39757. }
  39758. /**
  39759. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39760. * @returns true if the geometry can be regenerated
  39761. */
  39762. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39763. return this._canBeRegenerated;
  39764. };
  39765. /**
  39766. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39767. */
  39768. _PrimitiveGeometry.prototype.regenerate = function () {
  39769. if (!this._canBeRegenerated) {
  39770. return;
  39771. }
  39772. this._beingRegenerated = true;
  39773. this.setAllVerticesData(this._regenerateVertexData(), false);
  39774. this._beingRegenerated = false;
  39775. };
  39776. /**
  39777. * Clone the geometry
  39778. * @param id defines the unique ID of the new geometry
  39779. * @returns the new geometry
  39780. */
  39781. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39782. return _super.prototype.copy.call(this, id);
  39783. };
  39784. // overrides
  39785. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39786. if (!this._beingRegenerated) {
  39787. return;
  39788. }
  39789. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39790. };
  39791. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39792. if (!this._beingRegenerated) {
  39793. return;
  39794. }
  39795. _super.prototype.setVerticesData.call(this, kind, data, false);
  39796. };
  39797. // to override
  39798. /** @hidden */
  39799. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39800. throw new Error("Abstract method");
  39801. };
  39802. _PrimitiveGeometry.prototype.copy = function (id) {
  39803. throw new Error("Must be overriden in sub-classes.");
  39804. };
  39805. _PrimitiveGeometry.prototype.serialize = function () {
  39806. var serializationObject = _super.prototype.serialize.call(this);
  39807. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39808. return serializationObject;
  39809. };
  39810. return _PrimitiveGeometry;
  39811. }(Geometry));
  39812. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39813. /**
  39814. * Creates a ribbon geometry
  39815. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39816. */
  39817. var RibbonGeometry = /** @class */ (function (_super) {
  39818. __extends(RibbonGeometry, _super);
  39819. /**
  39820. * Creates a ribbon geometry
  39821. * @param id defines the unique ID of the geometry
  39822. * @param scene defines the hosting scene
  39823. * @param pathArray defines the array of paths to use
  39824. * @param closeArray defines if the last path and the first path must be joined
  39825. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39826. * @param offset defines the offset between points
  39827. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39828. * @param mesh defines the hosting mesh (can be null)
  39829. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39830. */
  39831. function RibbonGeometry(id, scene,
  39832. /**
  39833. * Defines the array of paths to use
  39834. */
  39835. pathArray,
  39836. /**
  39837. * Defines if the last and first points of each path in your pathArray must be joined
  39838. */
  39839. closeArray,
  39840. /**
  39841. * Defines if the last and first points of each path in your pathArray must be joined
  39842. */
  39843. closePath,
  39844. /**
  39845. * Defines the offset between points
  39846. */
  39847. offset, canBeRegenerated, mesh,
  39848. /**
  39849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39850. */
  39851. side) {
  39852. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39854. _this.pathArray = pathArray;
  39855. _this.closeArray = closeArray;
  39856. _this.closePath = closePath;
  39857. _this.offset = offset;
  39858. _this.side = side;
  39859. return _this;
  39860. }
  39861. /** @hidden */
  39862. RibbonGeometry.prototype._regenerateVertexData = function () {
  39863. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39864. };
  39865. RibbonGeometry.prototype.copy = function (id) {
  39866. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39867. };
  39868. return RibbonGeometry;
  39869. }(_PrimitiveGeometry));
  39870. BABYLON.RibbonGeometry = RibbonGeometry;
  39871. /**
  39872. * Creates a box geometry
  39873. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39874. */
  39875. var BoxGeometry = /** @class */ (function (_super) {
  39876. __extends(BoxGeometry, _super);
  39877. /**
  39878. * Creates a box geometry
  39879. * @param id defines the unique ID of the geometry
  39880. * @param scene defines the hosting scene
  39881. * @param size defines the zise of the box (width, height and depth are the same)
  39882. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39883. * @param mesh defines the hosting mesh (can be null)
  39884. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39885. */
  39886. function BoxGeometry(id, scene,
  39887. /**
  39888. * Defines the zise of the box (width, height and depth are the same)
  39889. */
  39890. size, canBeRegenerated, mesh,
  39891. /**
  39892. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39893. */
  39894. side) {
  39895. if (mesh === void 0) { mesh = null; }
  39896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39898. _this.size = size;
  39899. _this.side = side;
  39900. return _this;
  39901. }
  39902. BoxGeometry.prototype._regenerateVertexData = function () {
  39903. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39904. };
  39905. BoxGeometry.prototype.copy = function (id) {
  39906. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39907. };
  39908. BoxGeometry.prototype.serialize = function () {
  39909. var serializationObject = _super.prototype.serialize.call(this);
  39910. serializationObject.size = this.size;
  39911. return serializationObject;
  39912. };
  39913. BoxGeometry.Parse = function (parsedBox, scene) {
  39914. if (scene.getGeometryByID(parsedBox.id)) {
  39915. return null; // null since geometry could be something else than a box...
  39916. }
  39917. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39918. if (BABYLON.Tags) {
  39919. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39920. }
  39921. scene.pushGeometry(box, true);
  39922. return box;
  39923. };
  39924. return BoxGeometry;
  39925. }(_PrimitiveGeometry));
  39926. BABYLON.BoxGeometry = BoxGeometry;
  39927. /**
  39928. * Creates a sphere geometry
  39929. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39930. */
  39931. var SphereGeometry = /** @class */ (function (_super) {
  39932. __extends(SphereGeometry, _super);
  39933. /**
  39934. * Create a new sphere geometry
  39935. * @param id defines the unique ID of the geometry
  39936. * @param scene defines the hosting scene
  39937. * @param segments defines the number of segments to use to create the sphere
  39938. * @param diameter defines the diameter of the sphere
  39939. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39940. * @param mesh defines the hosting mesh (can be null)
  39941. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39942. */
  39943. function SphereGeometry(id, scene,
  39944. /**
  39945. * Defines the number of segments to use to create the sphere
  39946. */
  39947. segments,
  39948. /**
  39949. * Defines the diameter of the sphere
  39950. */
  39951. diameter, canBeRegenerated, mesh,
  39952. /**
  39953. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39954. */
  39955. side) {
  39956. if (mesh === void 0) { mesh = null; }
  39957. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39958. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39959. _this.segments = segments;
  39960. _this.diameter = diameter;
  39961. _this.side = side;
  39962. return _this;
  39963. }
  39964. SphereGeometry.prototype._regenerateVertexData = function () {
  39965. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39966. };
  39967. SphereGeometry.prototype.copy = function (id) {
  39968. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39969. };
  39970. SphereGeometry.prototype.serialize = function () {
  39971. var serializationObject = _super.prototype.serialize.call(this);
  39972. serializationObject.segments = this.segments;
  39973. serializationObject.diameter = this.diameter;
  39974. return serializationObject;
  39975. };
  39976. SphereGeometry.Parse = function (parsedSphere, scene) {
  39977. if (scene.getGeometryByID(parsedSphere.id)) {
  39978. return null; // null since geometry could be something else than a sphere...
  39979. }
  39980. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39981. if (BABYLON.Tags) {
  39982. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39983. }
  39984. scene.pushGeometry(sphere, true);
  39985. return sphere;
  39986. };
  39987. return SphereGeometry;
  39988. }(_PrimitiveGeometry));
  39989. BABYLON.SphereGeometry = SphereGeometry;
  39990. /**
  39991. * Creates a disc geometry
  39992. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39993. */
  39994. var DiscGeometry = /** @class */ (function (_super) {
  39995. __extends(DiscGeometry, _super);
  39996. /**
  39997. * Creates a new disc geometry
  39998. * @param id defines the unique ID of the geometry
  39999. * @param scene defines the hosting scene
  40000. * @param radius defines the radius of the disc
  40001. * @param tessellation defines the tesselation factor to apply to the disc
  40002. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40003. * @param mesh defines the hosting mesh (can be null)
  40004. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40005. */
  40006. function DiscGeometry(id, scene,
  40007. /**
  40008. * Defines the radius of the disc
  40009. */
  40010. radius,
  40011. /**
  40012. * Defines the tesselation factor to apply to the disc
  40013. */
  40014. tessellation, canBeRegenerated, mesh,
  40015. /**
  40016. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40017. */
  40018. side) {
  40019. if (mesh === void 0) { mesh = null; }
  40020. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40021. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40022. _this.radius = radius;
  40023. _this.tessellation = tessellation;
  40024. _this.side = side;
  40025. return _this;
  40026. }
  40027. DiscGeometry.prototype._regenerateVertexData = function () {
  40028. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40029. };
  40030. DiscGeometry.prototype.copy = function (id) {
  40031. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40032. };
  40033. return DiscGeometry;
  40034. }(_PrimitiveGeometry));
  40035. BABYLON.DiscGeometry = DiscGeometry;
  40036. /**
  40037. * Creates a new cylinder geometry
  40038. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40039. */
  40040. var CylinderGeometry = /** @class */ (function (_super) {
  40041. __extends(CylinderGeometry, _super);
  40042. /**
  40043. * Creates a new cylinder geometry
  40044. * @param id defines the unique ID of the geometry
  40045. * @param scene defines the hosting scene
  40046. * @param height defines the height of the cylinder
  40047. * @param diameterTop defines the diameter of the cylinder's top cap
  40048. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40049. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40050. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40051. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40052. * @param mesh defines the hosting mesh (can be null)
  40053. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40054. */
  40055. function CylinderGeometry(id, scene,
  40056. /**
  40057. * Defines the height of the cylinder
  40058. */
  40059. height,
  40060. /**
  40061. * Defines the diameter of the cylinder's top cap
  40062. */
  40063. diameterTop,
  40064. /**
  40065. * Defines the diameter of the cylinder's bottom cap
  40066. */
  40067. diameterBottom,
  40068. /**
  40069. * Defines the tessellation factor to apply to the cylinder
  40070. */
  40071. tessellation,
  40072. /**
  40073. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40074. */
  40075. subdivisions, canBeRegenerated, mesh,
  40076. /**
  40077. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40078. */
  40079. side) {
  40080. if (subdivisions === void 0) { subdivisions = 1; }
  40081. if (mesh === void 0) { mesh = null; }
  40082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40083. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40084. _this.height = height;
  40085. _this.diameterTop = diameterTop;
  40086. _this.diameterBottom = diameterBottom;
  40087. _this.tessellation = tessellation;
  40088. _this.subdivisions = subdivisions;
  40089. _this.side = side;
  40090. return _this;
  40091. }
  40092. CylinderGeometry.prototype._regenerateVertexData = function () {
  40093. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40094. };
  40095. CylinderGeometry.prototype.copy = function (id) {
  40096. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40097. };
  40098. CylinderGeometry.prototype.serialize = function () {
  40099. var serializationObject = _super.prototype.serialize.call(this);
  40100. serializationObject.height = this.height;
  40101. serializationObject.diameterTop = this.diameterTop;
  40102. serializationObject.diameterBottom = this.diameterBottom;
  40103. serializationObject.tessellation = this.tessellation;
  40104. return serializationObject;
  40105. };
  40106. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40107. if (scene.getGeometryByID(parsedCylinder.id)) {
  40108. return null; // null since geometry could be something else than a cylinder...
  40109. }
  40110. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40111. if (BABYLON.Tags) {
  40112. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40113. }
  40114. scene.pushGeometry(cylinder, true);
  40115. return cylinder;
  40116. };
  40117. return CylinderGeometry;
  40118. }(_PrimitiveGeometry));
  40119. BABYLON.CylinderGeometry = CylinderGeometry;
  40120. /**
  40121. * Creates a new torus geometry
  40122. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40123. */
  40124. var TorusGeometry = /** @class */ (function (_super) {
  40125. __extends(TorusGeometry, _super);
  40126. /**
  40127. * Creates a new torus geometry
  40128. * @param id defines the unique ID of the geometry
  40129. * @param scene defines the hosting scene
  40130. * @param diameter defines the diameter of the torus
  40131. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40132. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40134. * @param mesh defines the hosting mesh (can be null)
  40135. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40136. */
  40137. function TorusGeometry(id, scene,
  40138. /**
  40139. * Defines the diameter of the torus
  40140. */
  40141. diameter,
  40142. /**
  40143. * Defines the thickness of the torus (ie. internal diameter)
  40144. */
  40145. thickness,
  40146. /**
  40147. * Defines the tesselation factor to apply to the torus
  40148. */
  40149. tessellation, canBeRegenerated, mesh,
  40150. /**
  40151. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40152. */
  40153. side) {
  40154. if (mesh === void 0) { mesh = null; }
  40155. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40156. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40157. _this.diameter = diameter;
  40158. _this.thickness = thickness;
  40159. _this.tessellation = tessellation;
  40160. _this.side = side;
  40161. return _this;
  40162. }
  40163. TorusGeometry.prototype._regenerateVertexData = function () {
  40164. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40165. };
  40166. TorusGeometry.prototype.copy = function (id) {
  40167. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40168. };
  40169. TorusGeometry.prototype.serialize = function () {
  40170. var serializationObject = _super.prototype.serialize.call(this);
  40171. serializationObject.diameter = this.diameter;
  40172. serializationObject.thickness = this.thickness;
  40173. serializationObject.tessellation = this.tessellation;
  40174. return serializationObject;
  40175. };
  40176. TorusGeometry.Parse = function (parsedTorus, scene) {
  40177. if (scene.getGeometryByID(parsedTorus.id)) {
  40178. return null; // null since geometry could be something else than a torus...
  40179. }
  40180. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40181. if (BABYLON.Tags) {
  40182. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40183. }
  40184. scene.pushGeometry(torus, true);
  40185. return torus;
  40186. };
  40187. return TorusGeometry;
  40188. }(_PrimitiveGeometry));
  40189. BABYLON.TorusGeometry = TorusGeometry;
  40190. /**
  40191. * Creates a new ground geometry
  40192. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40193. */
  40194. var GroundGeometry = /** @class */ (function (_super) {
  40195. __extends(GroundGeometry, _super);
  40196. /**
  40197. * Creates a new ground geometry
  40198. * @param id defines the unique ID of the geometry
  40199. * @param scene defines the hosting scene
  40200. * @param width defines the width of the ground
  40201. * @param height defines the height of the ground
  40202. * @param subdivisions defines the subdivisions to apply to the ground
  40203. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40204. * @param mesh defines the hosting mesh (can be null)
  40205. */
  40206. function GroundGeometry(id, scene,
  40207. /**
  40208. * Defines the width of the ground
  40209. */
  40210. width,
  40211. /**
  40212. * Defines the height of the ground
  40213. */
  40214. height,
  40215. /**
  40216. * Defines the subdivisions to apply to the ground
  40217. */
  40218. subdivisions, canBeRegenerated, mesh) {
  40219. if (mesh === void 0) { mesh = null; }
  40220. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40221. _this.width = width;
  40222. _this.height = height;
  40223. _this.subdivisions = subdivisions;
  40224. return _this;
  40225. }
  40226. GroundGeometry.prototype._regenerateVertexData = function () {
  40227. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40228. };
  40229. GroundGeometry.prototype.copy = function (id) {
  40230. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40231. };
  40232. GroundGeometry.prototype.serialize = function () {
  40233. var serializationObject = _super.prototype.serialize.call(this);
  40234. serializationObject.width = this.width;
  40235. serializationObject.height = this.height;
  40236. serializationObject.subdivisions = this.subdivisions;
  40237. return serializationObject;
  40238. };
  40239. GroundGeometry.Parse = function (parsedGround, scene) {
  40240. if (scene.getGeometryByID(parsedGround.id)) {
  40241. return null; // null since geometry could be something else than a ground...
  40242. }
  40243. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40244. if (BABYLON.Tags) {
  40245. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40246. }
  40247. scene.pushGeometry(ground, true);
  40248. return ground;
  40249. };
  40250. return GroundGeometry;
  40251. }(_PrimitiveGeometry));
  40252. BABYLON.GroundGeometry = GroundGeometry;
  40253. /**
  40254. * Creates a tiled ground geometry
  40255. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40256. */
  40257. var TiledGroundGeometry = /** @class */ (function (_super) {
  40258. __extends(TiledGroundGeometry, _super);
  40259. /**
  40260. * Creates a tiled ground geometry
  40261. * @param id defines the unique ID of the geometry
  40262. * @param scene defines the hosting scene
  40263. * @param xmin defines the minimum value on X axis
  40264. * @param zmin defines the minimum value on Z axis
  40265. * @param xmax defines the maximum value on X axis
  40266. * @param zmax defines the maximum value on Z axis
  40267. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40268. * @param precision defines the precision to use when computing the tiles
  40269. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40270. * @param mesh defines the hosting mesh (can be null)
  40271. */
  40272. function TiledGroundGeometry(id, scene,
  40273. /**
  40274. * Defines the minimum value on X axis
  40275. */
  40276. xmin,
  40277. /**
  40278. * Defines the minimum value on Z axis
  40279. */
  40280. zmin,
  40281. /**
  40282. * Defines the maximum value on X axis
  40283. */
  40284. xmax,
  40285. /**
  40286. * Defines the maximum value on Z axis
  40287. */
  40288. zmax,
  40289. /**
  40290. * Defines the subdivisions to apply to the ground
  40291. */
  40292. subdivisions,
  40293. /**
  40294. * Defines the precision to use when computing the tiles
  40295. */
  40296. precision, canBeRegenerated, mesh) {
  40297. if (mesh === void 0) { mesh = null; }
  40298. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40299. _this.xmin = xmin;
  40300. _this.zmin = zmin;
  40301. _this.xmax = xmax;
  40302. _this.zmax = zmax;
  40303. _this.subdivisions = subdivisions;
  40304. _this.precision = precision;
  40305. return _this;
  40306. }
  40307. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40308. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40309. };
  40310. TiledGroundGeometry.prototype.copy = function (id) {
  40311. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40312. };
  40313. return TiledGroundGeometry;
  40314. }(_PrimitiveGeometry));
  40315. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40316. /**
  40317. * Creates a plane geometry
  40318. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40319. */
  40320. var PlaneGeometry = /** @class */ (function (_super) {
  40321. __extends(PlaneGeometry, _super);
  40322. /**
  40323. * Creates a plane geometry
  40324. * @param id defines the unique ID of the geometry
  40325. * @param scene defines the hosting scene
  40326. * @param size defines the size of the plane (width === height)
  40327. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40328. * @param mesh defines the hosting mesh (can be null)
  40329. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40330. */
  40331. function PlaneGeometry(id, scene,
  40332. /**
  40333. * Defines the size of the plane (width === height)
  40334. */
  40335. size, canBeRegenerated, mesh,
  40336. /**
  40337. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40338. */
  40339. side) {
  40340. if (mesh === void 0) { mesh = null; }
  40341. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40342. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40343. _this.size = size;
  40344. _this.side = side;
  40345. return _this;
  40346. }
  40347. PlaneGeometry.prototype._regenerateVertexData = function () {
  40348. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40349. };
  40350. PlaneGeometry.prototype.copy = function (id) {
  40351. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40352. };
  40353. PlaneGeometry.prototype.serialize = function () {
  40354. var serializationObject = _super.prototype.serialize.call(this);
  40355. serializationObject.size = this.size;
  40356. return serializationObject;
  40357. };
  40358. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40359. if (scene.getGeometryByID(parsedPlane.id)) {
  40360. return null; // null since geometry could be something else than a ground...
  40361. }
  40362. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40363. if (BABYLON.Tags) {
  40364. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40365. }
  40366. scene.pushGeometry(plane, true);
  40367. return plane;
  40368. };
  40369. return PlaneGeometry;
  40370. }(_PrimitiveGeometry));
  40371. BABYLON.PlaneGeometry = PlaneGeometry;
  40372. /**
  40373. * Creates a torus knot geometry
  40374. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40375. */
  40376. var TorusKnotGeometry = /** @class */ (function (_super) {
  40377. __extends(TorusKnotGeometry, _super);
  40378. /**
  40379. * Creates a torus knot geometry
  40380. * @param id defines the unique ID of the geometry
  40381. * @param scene defines the hosting scene
  40382. * @param radius defines the radius of the torus knot
  40383. * @param tube defines the thickness of the torus knot tube
  40384. * @param radialSegments defines the number of radial segments
  40385. * @param tubularSegments defines the number of tubular segments
  40386. * @param p defines the first number of windings
  40387. * @param q defines the second number of windings
  40388. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40389. * @param mesh defines the hosting mesh (can be null)
  40390. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40391. */
  40392. function TorusKnotGeometry(id, scene,
  40393. /**
  40394. * Defines the radius of the torus knot
  40395. */
  40396. radius,
  40397. /**
  40398. * Defines the thickness of the torus knot tube
  40399. */
  40400. tube,
  40401. /**
  40402. * Defines the number of radial segments
  40403. */
  40404. radialSegments,
  40405. /**
  40406. * Defines the number of tubular segments
  40407. */
  40408. tubularSegments,
  40409. /**
  40410. * Defines the first number of windings
  40411. */
  40412. p,
  40413. /**
  40414. * Defines the second number of windings
  40415. */
  40416. q, canBeRegenerated, mesh,
  40417. /**
  40418. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40419. */
  40420. side) {
  40421. if (mesh === void 0) { mesh = null; }
  40422. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40423. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40424. _this.radius = radius;
  40425. _this.tube = tube;
  40426. _this.radialSegments = radialSegments;
  40427. _this.tubularSegments = tubularSegments;
  40428. _this.p = p;
  40429. _this.q = q;
  40430. _this.side = side;
  40431. return _this;
  40432. }
  40433. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40434. 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 });
  40435. };
  40436. TorusKnotGeometry.prototype.copy = function (id) {
  40437. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40438. };
  40439. TorusKnotGeometry.prototype.serialize = function () {
  40440. var serializationObject = _super.prototype.serialize.call(this);
  40441. serializationObject.radius = this.radius;
  40442. serializationObject.tube = this.tube;
  40443. serializationObject.radialSegments = this.radialSegments;
  40444. serializationObject.tubularSegments = this.tubularSegments;
  40445. serializationObject.p = this.p;
  40446. serializationObject.q = this.q;
  40447. return serializationObject;
  40448. };
  40449. ;
  40450. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40451. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40452. return null; // null since geometry could be something else than a ground...
  40453. }
  40454. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40455. if (BABYLON.Tags) {
  40456. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40457. }
  40458. scene.pushGeometry(torusKnot, true);
  40459. return torusKnot;
  40460. };
  40461. return TorusKnotGeometry;
  40462. }(_PrimitiveGeometry));
  40463. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40464. //}
  40465. })(BABYLON || (BABYLON = {}));
  40466. //# sourceMappingURL=babylon.geometry.js.map
  40467. var BABYLON;
  40468. (function (BABYLON) {
  40469. /**
  40470. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40471. */
  40472. var PerformanceMonitor = /** @class */ (function () {
  40473. /**
  40474. * constructor
  40475. * @param frameSampleSize The number of samples required to saturate the sliding window
  40476. */
  40477. function PerformanceMonitor(frameSampleSize) {
  40478. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40479. this._enabled = true;
  40480. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40481. }
  40482. /**
  40483. * Samples current frame
  40484. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40485. */
  40486. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40487. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40488. if (!this._enabled)
  40489. return;
  40490. if (this._lastFrameTimeMs != null) {
  40491. var dt = timeMs - this._lastFrameTimeMs;
  40492. this._rollingFrameTime.add(dt);
  40493. }
  40494. this._lastFrameTimeMs = timeMs;
  40495. };
  40496. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40497. /**
  40498. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40499. * @return Average frame time in milliseconds
  40500. */
  40501. get: function () {
  40502. return this._rollingFrameTime.average;
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40508. /**
  40509. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40510. * @return Frame time variance in milliseconds squared
  40511. */
  40512. get: function () {
  40513. return this._rollingFrameTime.variance;
  40514. },
  40515. enumerable: true,
  40516. configurable: true
  40517. });
  40518. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40519. /**
  40520. * Returns the frame time of the most recent frame
  40521. * @return Frame time in milliseconds
  40522. */
  40523. get: function () {
  40524. return this._rollingFrameTime.history(0);
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40530. /**
  40531. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40532. * @return Framerate in frames per second
  40533. */
  40534. get: function () {
  40535. return 1000.0 / this._rollingFrameTime.average;
  40536. },
  40537. enumerable: true,
  40538. configurable: true
  40539. });
  40540. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40541. /**
  40542. * Returns the average framerate in frames per second using the most recent frame time
  40543. * @return Framerate in frames per second
  40544. */
  40545. get: function () {
  40546. var history = this._rollingFrameTime.history(0);
  40547. if (history === 0) {
  40548. return 0;
  40549. }
  40550. return 1000.0 / history;
  40551. },
  40552. enumerable: true,
  40553. configurable: true
  40554. });
  40555. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40556. /**
  40557. * Returns true if enough samples have been taken to completely fill the sliding window
  40558. * @return true if saturated
  40559. */
  40560. get: function () {
  40561. return this._rollingFrameTime.isSaturated();
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. /**
  40567. * Enables contributions to the sliding window sample set
  40568. */
  40569. PerformanceMonitor.prototype.enable = function () {
  40570. this._enabled = true;
  40571. };
  40572. /**
  40573. * Disables contributions to the sliding window sample set
  40574. * Samples will not be interpolated over the disabled period
  40575. */
  40576. PerformanceMonitor.prototype.disable = function () {
  40577. this._enabled = false;
  40578. //clear last sample to avoid interpolating over the disabled period when next enabled
  40579. this._lastFrameTimeMs = null;
  40580. };
  40581. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40582. /**
  40583. * Returns true if sampling is enabled
  40584. * @return true if enabled
  40585. */
  40586. get: function () {
  40587. return this._enabled;
  40588. },
  40589. enumerable: true,
  40590. configurable: true
  40591. });
  40592. /**
  40593. * Resets performance monitor
  40594. */
  40595. PerformanceMonitor.prototype.reset = function () {
  40596. //clear last sample to avoid interpolating over the disabled period when next enabled
  40597. this._lastFrameTimeMs = null;
  40598. //wipe record
  40599. this._rollingFrameTime.reset();
  40600. };
  40601. return PerformanceMonitor;
  40602. }());
  40603. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40604. /**
  40605. * RollingAverage
  40606. *
  40607. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40608. */
  40609. var RollingAverage = /** @class */ (function () {
  40610. /**
  40611. * constructor
  40612. * @param length The number of samples required to saturate the sliding window
  40613. */
  40614. function RollingAverage(length) {
  40615. this._samples = new Array(length);
  40616. this.reset();
  40617. }
  40618. /**
  40619. * Adds a sample to the sample set
  40620. * @param v The sample value
  40621. */
  40622. RollingAverage.prototype.add = function (v) {
  40623. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40624. var delta;
  40625. //we need to check if we've already wrapped round
  40626. if (this.isSaturated()) {
  40627. //remove bottom of stack from mean
  40628. var bottomValue = this._samples[this._pos];
  40629. delta = bottomValue - this.average;
  40630. this.average -= delta / (this._sampleCount - 1);
  40631. this._m2 -= delta * (bottomValue - this.average);
  40632. }
  40633. else {
  40634. this._sampleCount++;
  40635. }
  40636. //add new value to mean
  40637. delta = v - this.average;
  40638. this.average += delta / (this._sampleCount);
  40639. this._m2 += delta * (v - this.average);
  40640. //set the new variance
  40641. this.variance = this._m2 / (this._sampleCount - 1);
  40642. this._samples[this._pos] = v;
  40643. this._pos++;
  40644. this._pos %= this._samples.length; //positive wrap around
  40645. };
  40646. /**
  40647. * Returns previously added values or null if outside of history or outside the sliding window domain
  40648. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40649. * @return Value previously recorded with add() or null if outside of range
  40650. */
  40651. RollingAverage.prototype.history = function (i) {
  40652. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40653. return 0;
  40654. }
  40655. var i0 = this._wrapPosition(this._pos - 1.0);
  40656. return this._samples[this._wrapPosition(i0 - i)];
  40657. };
  40658. /**
  40659. * Returns true if enough samples have been taken to completely fill the sliding window
  40660. * @return true if sample-set saturated
  40661. */
  40662. RollingAverage.prototype.isSaturated = function () {
  40663. return this._sampleCount >= this._samples.length;
  40664. };
  40665. /**
  40666. * Resets the rolling average (equivalent to 0 samples taken so far)
  40667. */
  40668. RollingAverage.prototype.reset = function () {
  40669. this.average = 0;
  40670. this.variance = 0;
  40671. this._sampleCount = 0;
  40672. this._pos = 0;
  40673. this._m2 = 0;
  40674. };
  40675. /**
  40676. * Wraps a value around the sample range boundaries
  40677. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40678. * @return Wrapped position in sample range
  40679. */
  40680. RollingAverage.prototype._wrapPosition = function (i) {
  40681. var max = this._samples.length;
  40682. return ((i % max) + max) % max;
  40683. };
  40684. return RollingAverage;
  40685. }());
  40686. BABYLON.RollingAverage = RollingAverage;
  40687. })(BABYLON || (BABYLON = {}));
  40688. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40689. var BABYLON;
  40690. (function (BABYLON) {
  40691. /**
  40692. * "Static Class" containing the most commonly used helper while dealing with material for
  40693. * rendering purpose.
  40694. *
  40695. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40696. *
  40697. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40698. */
  40699. var MaterialHelper = /** @class */ (function () {
  40700. function MaterialHelper() {
  40701. }
  40702. /**
  40703. * Bind the current view position to an effect.
  40704. * @param effect The effect to be bound
  40705. * @param scene The scene the eyes position is used from
  40706. */
  40707. MaterialHelper.BindEyePosition = function (effect, scene) {
  40708. if (scene._forcedViewPosition) {
  40709. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40710. return;
  40711. }
  40712. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40713. };
  40714. /**
  40715. * Helps preparing the defines values about the UVs in used in the effect.
  40716. * UVs are shared as much as we can accross chanels in the shaders.
  40717. * @param texture The texture we are preparing the UVs for
  40718. * @param defines The defines to update
  40719. * @param key The chanel key "diffuse", "specular"... used in the shader
  40720. */
  40721. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40722. defines._needUVs = true;
  40723. defines[key] = true;
  40724. if (texture.getTextureMatrix().isIdentity(true)) {
  40725. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40726. if (texture.coordinatesIndex === 0) {
  40727. defines["MAINUV1"] = true;
  40728. }
  40729. else {
  40730. defines["MAINUV2"] = true;
  40731. }
  40732. }
  40733. else {
  40734. defines[key + "DIRECTUV"] = 0;
  40735. }
  40736. };
  40737. /**
  40738. * Binds a texture matrix value to its corrsponding uniform
  40739. * @param texture The texture to bind the matrix for
  40740. * @param uniformBuffer The uniform buffer receivin the data
  40741. * @param key The chanel key "diffuse", "specular"... used in the shader
  40742. */
  40743. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40744. var matrix = texture.getTextureMatrix();
  40745. if (!matrix.isIdentity(true)) {
  40746. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40747. }
  40748. };
  40749. /**
  40750. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40751. * @param mesh defines the current mesh
  40752. * @param scene defines the current scene
  40753. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40754. * @param pointsCloud defines if point cloud rendering has to be turned on
  40755. * @param fogEnabled defines if fog has to be turned on
  40756. * @param alphaTest defines if alpha testing has to be turned on
  40757. * @param defines defines the current list of defines
  40758. */
  40759. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40760. if (defines._areMiscDirty) {
  40761. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40762. defines["POINTSIZE"] = pointsCloud;
  40763. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40764. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40765. defines["ALPHATEST"] = alphaTest;
  40766. }
  40767. };
  40768. /**
  40769. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40770. * @param scene defines the current scene
  40771. * @param engine defines the current engine
  40772. * @param defines specifies the list of active defines
  40773. * @param useInstances defines if instances have to be turned on
  40774. * @param useClipPlane defines if clip plane have to be turned on
  40775. */
  40776. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40777. if (useClipPlane === void 0) { useClipPlane = null; }
  40778. var changed = false;
  40779. if (useClipPlane == null) {
  40780. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40781. }
  40782. if (defines["CLIPPLANE"] !== useClipPlane) {
  40783. defines["CLIPPLANE"] = useClipPlane;
  40784. changed = true;
  40785. }
  40786. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40787. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40788. changed = true;
  40789. }
  40790. if (defines["INSTANCES"] !== useInstances) {
  40791. defines["INSTANCES"] = useInstances;
  40792. changed = true;
  40793. }
  40794. if (changed) {
  40795. defines.markAsUnprocessed();
  40796. }
  40797. };
  40798. /**
  40799. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40800. * @param mesh The mesh containing the geometry data we will draw
  40801. * @param defines The defines to update
  40802. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40803. * @param useBones Precise whether bones should be used or not (override mesh info)
  40804. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40805. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40806. * @returns false if defines are considered not dirty and have not been checked
  40807. */
  40808. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40809. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40810. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40811. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40812. return false;
  40813. }
  40814. defines._normals = defines._needNormals;
  40815. defines._uvs = defines._needUVs;
  40816. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40817. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40818. defines["TANGENT"] = true;
  40819. }
  40820. if (defines._needUVs) {
  40821. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40822. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40823. }
  40824. else {
  40825. defines["UV1"] = false;
  40826. defines["UV2"] = false;
  40827. }
  40828. if (useVertexColor) {
  40829. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40830. defines["VERTEXCOLOR"] = hasVertexColors;
  40831. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40832. }
  40833. if (useBones) {
  40834. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40835. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40836. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40837. }
  40838. else {
  40839. defines["NUM_BONE_INFLUENCERS"] = 0;
  40840. defines["BonesPerMesh"] = 0;
  40841. }
  40842. }
  40843. if (useMorphTargets) {
  40844. var manager = mesh.morphTargetManager;
  40845. if (manager) {
  40846. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40847. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40848. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40849. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40850. }
  40851. else {
  40852. defines["MORPHTARGETS_TANGENT"] = false;
  40853. defines["MORPHTARGETS_NORMAL"] = false;
  40854. defines["MORPHTARGETS"] = false;
  40855. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40856. }
  40857. }
  40858. return true;
  40859. };
  40860. /**
  40861. * Prepares the defines related to the light information passed in parameter
  40862. * @param scene The scene we are intending to draw
  40863. * @param mesh The mesh the effect is compiling for
  40864. * @param defines The defines to update
  40865. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40866. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40867. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40868. * @returns true if normals will be required for the rest of the effect
  40869. */
  40870. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40871. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40872. if (disableLighting === void 0) { disableLighting = false; }
  40873. if (!defines._areLightsDirty) {
  40874. return defines._needNormals;
  40875. }
  40876. var lightIndex = 0;
  40877. var needNormals = false;
  40878. var needRebuild = false;
  40879. var lightmapMode = false;
  40880. var shadowEnabled = false;
  40881. var specularEnabled = false;
  40882. if (scene.lightsEnabled && !disableLighting) {
  40883. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40884. var light = _a[_i];
  40885. needNormals = true;
  40886. if (defines["LIGHT" + lightIndex] === undefined) {
  40887. needRebuild = true;
  40888. }
  40889. defines["LIGHT" + lightIndex] = true;
  40890. defines["SPOTLIGHT" + lightIndex] = false;
  40891. defines["HEMILIGHT" + lightIndex] = false;
  40892. defines["POINTLIGHT" + lightIndex] = false;
  40893. defines["DIRLIGHT" + lightIndex] = false;
  40894. light.prepareLightSpecificDefines(defines, lightIndex);
  40895. // Specular
  40896. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40897. specularEnabled = true;
  40898. }
  40899. // Shadows
  40900. defines["SHADOW" + lightIndex] = false;
  40901. defines["SHADOWPCF" + lightIndex] = false;
  40902. defines["SHADOWPCSS" + lightIndex] = false;
  40903. defines["SHADOWPOISSON" + lightIndex] = false;
  40904. defines["SHADOWESM" + lightIndex] = false;
  40905. defines["SHADOWCUBE" + lightIndex] = false;
  40906. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40907. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40908. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40909. var shadowGenerator = light.getShadowGenerator();
  40910. if (shadowGenerator) {
  40911. var shadowMap = shadowGenerator.getShadowMapForRendering();
  40912. if (shadowMap) {
  40913. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40914. shadowEnabled = true;
  40915. shadowGenerator.prepareDefines(defines, lightIndex);
  40916. }
  40917. }
  40918. }
  40919. }
  40920. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40921. lightmapMode = true;
  40922. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40923. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40924. }
  40925. else {
  40926. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40927. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40928. }
  40929. lightIndex++;
  40930. if (lightIndex === maxSimultaneousLights)
  40931. break;
  40932. }
  40933. }
  40934. defines["SPECULARTERM"] = specularEnabled;
  40935. defines["SHADOWS"] = shadowEnabled;
  40936. // Resetting all other lights if any
  40937. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40938. if (defines["LIGHT" + index] !== undefined) {
  40939. defines["LIGHT" + index] = false;
  40940. defines["HEMILIGHT" + lightIndex] = false;
  40941. defines["POINTLIGHT" + lightIndex] = false;
  40942. defines["DIRLIGHT" + lightIndex] = false;
  40943. defines["SPOTLIGHT" + lightIndex] = false;
  40944. defines["SHADOW" + lightIndex] = false;
  40945. }
  40946. }
  40947. var caps = scene.getEngine().getCaps();
  40948. if (defines["SHADOWFLOAT"] === undefined) {
  40949. needRebuild = true;
  40950. }
  40951. defines["SHADOWFLOAT"] = shadowEnabled &&
  40952. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40953. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40954. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40955. if (needRebuild) {
  40956. defines.rebuild();
  40957. }
  40958. return needNormals;
  40959. };
  40960. /**
  40961. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40962. * that won t be acctive due to defines being turned off.
  40963. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40964. * @param samplersList The samplers list
  40965. * @param defines The defines helping in the list generation
  40966. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40967. */
  40968. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40969. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40970. var uniformsList;
  40971. var uniformBuffersList = null;
  40972. if (uniformsListOrOptions.uniformsNames) {
  40973. var options = uniformsListOrOptions;
  40974. uniformsList = options.uniformsNames;
  40975. uniformBuffersList = options.uniformBuffersNames;
  40976. samplersList = options.samplers;
  40977. defines = options.defines;
  40978. maxSimultaneousLights = options.maxSimultaneousLights;
  40979. }
  40980. else {
  40981. uniformsList = uniformsListOrOptions;
  40982. if (!samplersList) {
  40983. samplersList = [];
  40984. }
  40985. }
  40986. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40987. if (!defines["LIGHT" + lightIndex]) {
  40988. break;
  40989. }
  40990. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40991. if (uniformBuffersList) {
  40992. uniformBuffersList.push("Light" + lightIndex);
  40993. }
  40994. samplersList.push("shadowSampler" + lightIndex);
  40995. samplersList.push("depthSampler" + lightIndex);
  40996. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40997. samplersList.push("projectionLightSampler" + lightIndex);
  40998. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40999. }
  41000. }
  41001. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41002. uniformsList.push("morphTargetInfluences");
  41003. }
  41004. };
  41005. /**
  41006. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41007. * @param defines The defines to update while falling back
  41008. * @param fallbacks The authorized effect fallbacks
  41009. * @param maxSimultaneousLights The maximum number of lights allowed
  41010. * @param rank the current rank of the Effect
  41011. * @returns The newly affected rank
  41012. */
  41013. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41014. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41015. if (rank === void 0) { rank = 0; }
  41016. var lightFallbackRank = 0;
  41017. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41018. if (!defines["LIGHT" + lightIndex]) {
  41019. break;
  41020. }
  41021. if (lightIndex > 0) {
  41022. lightFallbackRank = rank + lightIndex;
  41023. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41024. }
  41025. if (!defines["SHADOWS"]) {
  41026. if (defines["SHADOW" + lightIndex]) {
  41027. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41028. }
  41029. if (defines["SHADOWPCF" + lightIndex]) {
  41030. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41031. }
  41032. if (defines["SHADOWPCSS" + lightIndex]) {
  41033. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41034. }
  41035. if (defines["SHADOWPOISSON" + lightIndex]) {
  41036. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41037. }
  41038. if (defines["SHADOWESM" + lightIndex]) {
  41039. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41040. }
  41041. }
  41042. }
  41043. return lightFallbackRank++;
  41044. };
  41045. /**
  41046. * Prepares the list of attributes required for morph targets according to the effect defines.
  41047. * @param attribs The current list of supported attribs
  41048. * @param mesh The mesh to prepare the morph targets attributes for
  41049. * @param defines The current Defines of the effect
  41050. */
  41051. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41052. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41053. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41054. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41055. var manager = mesh.morphTargetManager;
  41056. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41057. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41058. for (var index = 0; index < influencers; index++) {
  41059. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41060. if (normal) {
  41061. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41062. }
  41063. if (tangent) {
  41064. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41065. }
  41066. if (attribs.length > maxAttributesCount) {
  41067. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41068. }
  41069. }
  41070. }
  41071. };
  41072. /**
  41073. * Prepares the list of attributes required for bones according to the effect defines.
  41074. * @param attribs The current list of supported attribs
  41075. * @param mesh The mesh to prepare the bones attributes for
  41076. * @param defines The current Defines of the effect
  41077. * @param fallbacks The current efffect fallback strategy
  41078. */
  41079. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41080. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41081. fallbacks.addCPUSkinningFallback(0, mesh);
  41082. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41083. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41084. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41085. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41086. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41087. }
  41088. }
  41089. };
  41090. /**
  41091. * Prepares the list of attributes required for instances according to the effect defines.
  41092. * @param attribs The current list of supported attribs
  41093. * @param defines The current Defines of the effect
  41094. */
  41095. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41096. if (defines["INSTANCES"]) {
  41097. attribs.push("world0");
  41098. attribs.push("world1");
  41099. attribs.push("world2");
  41100. attribs.push("world3");
  41101. }
  41102. };
  41103. /**
  41104. * Binds the light shadow information to the effect for the given mesh.
  41105. * @param light The light containing the generator
  41106. * @param scene The scene the lights belongs to
  41107. * @param mesh The mesh we are binding the information to render
  41108. * @param lightIndex The light index in the effect used to render the mesh
  41109. * @param effect The effect we are binding the data to
  41110. */
  41111. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41112. if (light.shadowEnabled && mesh.receiveShadows) {
  41113. var shadowGenerator = light.getShadowGenerator();
  41114. if (shadowGenerator) {
  41115. shadowGenerator.bindShadowLight(lightIndex, effect);
  41116. }
  41117. }
  41118. };
  41119. /**
  41120. * Binds the light information to the effect.
  41121. * @param light The light containing the generator
  41122. * @param effect The effect we are binding the data to
  41123. * @param lightIndex The light index in the effect used to render
  41124. */
  41125. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41126. light.transferToEffect(effect, lightIndex + "");
  41127. };
  41128. /**
  41129. * Binds the lights information from the scene to the effect for the given mesh.
  41130. * @param scene The scene the lights belongs to
  41131. * @param mesh The mesh we are binding the information to render
  41132. * @param effect The effect we are binding the data to
  41133. * @param defines The generated defines for the effect
  41134. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41135. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41136. */
  41137. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41138. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41139. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41140. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41141. for (var i = 0; i < len; i++) {
  41142. var light = mesh._lightSources[i];
  41143. var iAsString = i.toString();
  41144. var scaledIntensity = light.getScaledIntensity();
  41145. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41146. MaterialHelper.BindLightProperties(light, effect, i);
  41147. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41148. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41149. if (defines["SPECULARTERM"]) {
  41150. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41151. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41152. }
  41153. // Shadows
  41154. if (scene.shadowsEnabled) {
  41155. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41156. }
  41157. light._uniformBuffer.update();
  41158. }
  41159. };
  41160. /**
  41161. * Binds the fog information from the scene to the effect for the given mesh.
  41162. * @param scene The scene the lights belongs to
  41163. * @param mesh The mesh we are binding the information to render
  41164. * @param effect The effect we are binding the data to
  41165. */
  41166. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41167. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41168. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41169. effect.setColor3("vFogColor", scene.fogColor);
  41170. }
  41171. };
  41172. /**
  41173. * Binds the bones information from the mesh to the effect.
  41174. * @param mesh The mesh we are binding the information to render
  41175. * @param effect The effect we are binding the data to
  41176. */
  41177. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41178. if (!effect || !mesh) {
  41179. return;
  41180. }
  41181. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41182. mesh.computeBonesUsingShaders = false;
  41183. }
  41184. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41185. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41186. if (matrices) {
  41187. effect.setMatrices("mBones", matrices);
  41188. }
  41189. }
  41190. };
  41191. /**
  41192. * Binds the morph targets information from the mesh to the effect.
  41193. * @param abstractMesh The mesh we are binding the information to render
  41194. * @param effect The effect we are binding the data to
  41195. */
  41196. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41197. var manager = abstractMesh.morphTargetManager;
  41198. if (!abstractMesh || !manager) {
  41199. return;
  41200. }
  41201. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41202. };
  41203. /**
  41204. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41205. * @param defines The generated defines used in the effect
  41206. * @param effect The effect we are binding the data to
  41207. * @param scene The scene we are willing to render with logarithmic scale for
  41208. */
  41209. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41210. if (defines["LOGARITHMICDEPTH"]) {
  41211. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41212. }
  41213. };
  41214. /**
  41215. * Binds the clip plane information from the scene to the effect.
  41216. * @param scene The scene the clip plane information are extracted from
  41217. * @param effect The effect we are binding the data to
  41218. */
  41219. MaterialHelper.BindClipPlane = function (effect, scene) {
  41220. if (scene.clipPlane) {
  41221. var clipPlane = scene.clipPlane;
  41222. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41223. }
  41224. };
  41225. return MaterialHelper;
  41226. }());
  41227. BABYLON.MaterialHelper = MaterialHelper;
  41228. })(BABYLON || (BABYLON = {}));
  41229. //# sourceMappingURL=babylon.materialHelper.js.map
  41230. var BABYLON;
  41231. (function (BABYLON) {
  41232. var PushMaterial = /** @class */ (function (_super) {
  41233. __extends(PushMaterial, _super);
  41234. function PushMaterial(name, scene) {
  41235. var _this = _super.call(this, name, scene) || this;
  41236. _this._normalMatrix = new BABYLON.Matrix();
  41237. _this.storeEffectOnSubMeshes = true;
  41238. return _this;
  41239. }
  41240. PushMaterial.prototype.getEffect = function () {
  41241. return this._activeEffect;
  41242. };
  41243. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41244. if (!mesh) {
  41245. return false;
  41246. }
  41247. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41248. return true;
  41249. }
  41250. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41251. };
  41252. /**
  41253. * Binds the given world matrix to the active effect
  41254. *
  41255. * @param world the matrix to bind
  41256. */
  41257. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41258. this._activeEffect.setMatrix("world", world);
  41259. };
  41260. /**
  41261. * Binds the given normal matrix to the active effect
  41262. *
  41263. * @param normalMatrix the matrix to bind
  41264. */
  41265. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41266. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41267. };
  41268. PushMaterial.prototype.bind = function (world, mesh) {
  41269. if (!mesh) {
  41270. return;
  41271. }
  41272. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41273. };
  41274. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41275. if (effect === void 0) { effect = null; }
  41276. _super.prototype._afterBind.call(this, mesh);
  41277. this.getScene()._cachedEffect = effect;
  41278. };
  41279. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41280. if (visibility === void 0) { visibility = 1; }
  41281. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41282. };
  41283. return PushMaterial;
  41284. }(BABYLON.Material));
  41285. BABYLON.PushMaterial = PushMaterial;
  41286. })(BABYLON || (BABYLON = {}));
  41287. //# sourceMappingURL=babylon.pushMaterial.js.map
  41288. var BABYLON;
  41289. (function (BABYLON) {
  41290. /** @hidden */
  41291. var StandardMaterialDefines = /** @class */ (function (_super) {
  41292. __extends(StandardMaterialDefines, _super);
  41293. function StandardMaterialDefines() {
  41294. var _this = _super.call(this) || this;
  41295. _this.MAINUV1 = false;
  41296. _this.MAINUV2 = false;
  41297. _this.DIFFUSE = false;
  41298. _this.DIFFUSEDIRECTUV = 0;
  41299. _this.AMBIENT = false;
  41300. _this.AMBIENTDIRECTUV = 0;
  41301. _this.OPACITY = false;
  41302. _this.OPACITYDIRECTUV = 0;
  41303. _this.OPACITYRGB = false;
  41304. _this.REFLECTION = false;
  41305. _this.EMISSIVE = false;
  41306. _this.EMISSIVEDIRECTUV = 0;
  41307. _this.SPECULAR = false;
  41308. _this.SPECULARDIRECTUV = 0;
  41309. _this.BUMP = false;
  41310. _this.BUMPDIRECTUV = 0;
  41311. _this.PARALLAX = false;
  41312. _this.PARALLAXOCCLUSION = false;
  41313. _this.SPECULAROVERALPHA = false;
  41314. _this.CLIPPLANE = false;
  41315. _this.ALPHATEST = false;
  41316. _this.DEPTHPREPASS = false;
  41317. _this.ALPHAFROMDIFFUSE = false;
  41318. _this.POINTSIZE = false;
  41319. _this.FOG = false;
  41320. _this.SPECULARTERM = false;
  41321. _this.DIFFUSEFRESNEL = false;
  41322. _this.OPACITYFRESNEL = false;
  41323. _this.REFLECTIONFRESNEL = false;
  41324. _this.REFRACTIONFRESNEL = false;
  41325. _this.EMISSIVEFRESNEL = false;
  41326. _this.FRESNEL = false;
  41327. _this.NORMAL = false;
  41328. _this.UV1 = false;
  41329. _this.UV2 = false;
  41330. _this.VERTEXCOLOR = false;
  41331. _this.VERTEXALPHA = false;
  41332. _this.NUM_BONE_INFLUENCERS = 0;
  41333. _this.BonesPerMesh = 0;
  41334. _this.INSTANCES = false;
  41335. _this.GLOSSINESS = false;
  41336. _this.ROUGHNESS = false;
  41337. _this.EMISSIVEASILLUMINATION = false;
  41338. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41339. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41340. _this.LIGHTMAP = false;
  41341. _this.LIGHTMAPDIRECTUV = 0;
  41342. _this.OBJECTSPACE_NORMALMAP = false;
  41343. _this.USELIGHTMAPASSHADOWMAP = false;
  41344. _this.REFLECTIONMAP_3D = false;
  41345. _this.REFLECTIONMAP_SPHERICAL = false;
  41346. _this.REFLECTIONMAP_PLANAR = false;
  41347. _this.REFLECTIONMAP_CUBIC = false;
  41348. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41349. _this.REFLECTIONMAP_PROJECTION = false;
  41350. _this.REFLECTIONMAP_SKYBOX = false;
  41351. _this.REFLECTIONMAP_EXPLICIT = false;
  41352. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41353. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41354. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41355. _this.INVERTCUBICMAP = false;
  41356. _this.LOGARITHMICDEPTH = false;
  41357. _this.REFRACTION = false;
  41358. _this.REFRACTIONMAP_3D = false;
  41359. _this.REFLECTIONOVERALPHA = false;
  41360. _this.TWOSIDEDLIGHTING = false;
  41361. _this.SHADOWFLOAT = false;
  41362. _this.MORPHTARGETS = false;
  41363. _this.MORPHTARGETS_NORMAL = false;
  41364. _this.MORPHTARGETS_TANGENT = false;
  41365. _this.NUM_MORPH_INFLUENCERS = 0;
  41366. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41367. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41368. _this.IMAGEPROCESSING = false;
  41369. _this.VIGNETTE = false;
  41370. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41371. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41372. _this.TONEMAPPING = false;
  41373. _this.CONTRAST = false;
  41374. _this.COLORCURVES = false;
  41375. _this.COLORGRADING = false;
  41376. _this.COLORGRADING3D = false;
  41377. _this.SAMPLER3DGREENDEPTH = false;
  41378. _this.SAMPLER3DBGRMAP = false;
  41379. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41380. /**
  41381. * If the reflection texture on this material is in linear color space
  41382. * @hidden
  41383. */
  41384. _this.IS_REFLECTION_LINEAR = false;
  41385. /**
  41386. * If the refraction texture on this material is in linear color space
  41387. * @hidden
  41388. */
  41389. _this.IS_REFRACTION_LINEAR = false;
  41390. _this.EXPOSURE = false;
  41391. _this.rebuild();
  41392. return _this;
  41393. }
  41394. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41395. var modes = [
  41396. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41397. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41398. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41399. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41400. ];
  41401. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41402. var mode = modes_1[_i];
  41403. this[mode] = (mode === modeToEnable);
  41404. }
  41405. };
  41406. return StandardMaterialDefines;
  41407. }(BABYLON.MaterialDefines));
  41408. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41409. var StandardMaterial = /** @class */ (function (_super) {
  41410. __extends(StandardMaterial, _super);
  41411. function StandardMaterial(name, scene) {
  41412. var _this = _super.call(this, name, scene) || this;
  41413. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41414. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41415. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41416. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41417. _this.specularPower = 64;
  41418. _this._useAlphaFromDiffuseTexture = false;
  41419. _this._useEmissiveAsIllumination = false;
  41420. _this._linkEmissiveWithDiffuse = false;
  41421. _this._useSpecularOverAlpha = false;
  41422. _this._useReflectionOverAlpha = false;
  41423. _this._disableLighting = false;
  41424. _this._useObjectSpaceNormalMap = false;
  41425. _this._useParallax = false;
  41426. _this._useParallaxOcclusion = false;
  41427. _this.parallaxScaleBias = 0.05;
  41428. _this._roughness = 0;
  41429. _this.indexOfRefraction = 0.98;
  41430. _this.invertRefractionY = true;
  41431. /**
  41432. * Defines the alpha limits in alpha test mode
  41433. */
  41434. _this.alphaCutOff = 0.4;
  41435. _this._useLightmapAsShadowmap = false;
  41436. _this._useReflectionFresnelFromSpecular = false;
  41437. _this._useGlossinessFromSpecularMapAlpha = false;
  41438. _this._maxSimultaneousLights = 4;
  41439. /**
  41440. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41441. */
  41442. _this._invertNormalMapX = false;
  41443. /**
  41444. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41445. */
  41446. _this._invertNormalMapY = false;
  41447. /**
  41448. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41449. */
  41450. _this._twoSidedLighting = false;
  41451. _this._renderTargets = new BABYLON.SmartArray(16);
  41452. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41453. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41454. // Setup the default processing configuration to the scene.
  41455. _this._attachImageProcessingConfiguration(null);
  41456. _this.getRenderTargetTextures = function () {
  41457. _this._renderTargets.reset();
  41458. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41459. _this._renderTargets.push(_this._reflectionTexture);
  41460. }
  41461. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41462. _this._renderTargets.push(_this._refractionTexture);
  41463. }
  41464. return _this._renderTargets;
  41465. };
  41466. return _this;
  41467. }
  41468. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41469. /**
  41470. * Gets the image processing configuration used either in this material.
  41471. */
  41472. get: function () {
  41473. return this._imageProcessingConfiguration;
  41474. },
  41475. /**
  41476. * Sets the Default image processing configuration used either in the this material.
  41477. *
  41478. * If sets to null, the scene one is in use.
  41479. */
  41480. set: function (value) {
  41481. this._attachImageProcessingConfiguration(value);
  41482. // Ensure the effect will be rebuilt.
  41483. this._markAllSubMeshesAsTexturesDirty();
  41484. },
  41485. enumerable: true,
  41486. configurable: true
  41487. });
  41488. /**
  41489. * Attaches a new image processing configuration to the Standard Material.
  41490. * @param configuration
  41491. */
  41492. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41493. var _this = this;
  41494. if (configuration === this._imageProcessingConfiguration) {
  41495. return;
  41496. }
  41497. // Detaches observer.
  41498. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41499. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41500. }
  41501. // Pick the scene configuration if needed.
  41502. if (!configuration) {
  41503. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41504. }
  41505. else {
  41506. this._imageProcessingConfiguration = configuration;
  41507. }
  41508. // Attaches observer.
  41509. if (this._imageProcessingConfiguration) {
  41510. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41511. _this._markAllSubMeshesAsImageProcessingDirty();
  41512. });
  41513. }
  41514. };
  41515. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41516. /**
  41517. * Gets wether the color curves effect is enabled.
  41518. */
  41519. get: function () {
  41520. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41521. },
  41522. /**
  41523. * Sets wether the color curves effect is enabled.
  41524. */
  41525. set: function (value) {
  41526. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41532. /**
  41533. * Gets wether the color grading effect is enabled.
  41534. */
  41535. get: function () {
  41536. return this.imageProcessingConfiguration.colorGradingEnabled;
  41537. },
  41538. /**
  41539. * Gets wether the color grading effect is enabled.
  41540. */
  41541. set: function (value) {
  41542. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41548. /**
  41549. * Gets wether tonemapping is enabled or not.
  41550. */
  41551. get: function () {
  41552. return this._imageProcessingConfiguration.toneMappingEnabled;
  41553. },
  41554. /**
  41555. * Sets wether tonemapping is enabled or not
  41556. */
  41557. set: function (value) {
  41558. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. ;
  41564. ;
  41565. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41566. /**
  41567. * The camera exposure used on this material.
  41568. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41569. * This corresponds to a photographic exposure.
  41570. */
  41571. get: function () {
  41572. return this._imageProcessingConfiguration.exposure;
  41573. },
  41574. /**
  41575. * The camera exposure used on this material.
  41576. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41577. * This corresponds to a photographic exposure.
  41578. */
  41579. set: function (value) {
  41580. this._imageProcessingConfiguration.exposure = value;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. ;
  41586. ;
  41587. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41588. /**
  41589. * Gets The camera contrast used on this material.
  41590. */
  41591. get: function () {
  41592. return this._imageProcessingConfiguration.contrast;
  41593. },
  41594. /**
  41595. * Sets The camera contrast used on this material.
  41596. */
  41597. set: function (value) {
  41598. this._imageProcessingConfiguration.contrast = value;
  41599. },
  41600. enumerable: true,
  41601. configurable: true
  41602. });
  41603. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41604. /**
  41605. * Gets the Color Grading 2D Lookup Texture.
  41606. */
  41607. get: function () {
  41608. return this._imageProcessingConfiguration.colorGradingTexture;
  41609. },
  41610. /**
  41611. * Sets the Color Grading 2D Lookup Texture.
  41612. */
  41613. set: function (value) {
  41614. this._imageProcessingConfiguration.colorGradingTexture = value;
  41615. },
  41616. enumerable: true,
  41617. configurable: true
  41618. });
  41619. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41620. /**
  41621. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41622. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41623. * 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;
  41624. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41625. */
  41626. get: function () {
  41627. return this._imageProcessingConfiguration.colorCurves;
  41628. },
  41629. /**
  41630. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41631. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41632. * 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;
  41633. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41634. */
  41635. set: function (value) {
  41636. this._imageProcessingConfiguration.colorCurves = value;
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. StandardMaterial.prototype.getClassName = function () {
  41642. return "StandardMaterial";
  41643. };
  41644. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41645. get: function () {
  41646. return this._useLogarithmicDepth;
  41647. },
  41648. set: function (value) {
  41649. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41650. this._markAllSubMeshesAsMiscDirty();
  41651. },
  41652. enumerable: true,
  41653. configurable: true
  41654. });
  41655. StandardMaterial.prototype.needAlphaBlending = function () {
  41656. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41657. };
  41658. StandardMaterial.prototype.needAlphaTesting = function () {
  41659. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41660. };
  41661. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41662. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41663. };
  41664. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41665. return this._diffuseTexture;
  41666. };
  41667. /**
  41668. * Child classes can use it to update shaders
  41669. */
  41670. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41671. if (useInstances === void 0) { useInstances = false; }
  41672. if (subMesh.effect && this.isFrozen) {
  41673. if (this._wasPreviouslyReady && subMesh.effect) {
  41674. return true;
  41675. }
  41676. }
  41677. if (!subMesh._materialDefines) {
  41678. subMesh._materialDefines = new StandardMaterialDefines();
  41679. }
  41680. var scene = this.getScene();
  41681. var defines = subMesh._materialDefines;
  41682. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41683. if (defines._renderId === scene.getRenderId()) {
  41684. return true;
  41685. }
  41686. }
  41687. var engine = scene.getEngine();
  41688. // Lights
  41689. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41690. // Textures
  41691. if (defines._areTexturesDirty) {
  41692. defines._needUVs = false;
  41693. defines.MAINUV1 = false;
  41694. defines.MAINUV2 = false;
  41695. if (scene.texturesEnabled) {
  41696. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41697. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41698. return false;
  41699. }
  41700. else {
  41701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41702. }
  41703. }
  41704. else {
  41705. defines.DIFFUSE = false;
  41706. }
  41707. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41708. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41709. return false;
  41710. }
  41711. else {
  41712. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41713. }
  41714. }
  41715. else {
  41716. defines.AMBIENT = false;
  41717. }
  41718. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41719. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41720. return false;
  41721. }
  41722. else {
  41723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41724. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41725. }
  41726. }
  41727. else {
  41728. defines.OPACITY = false;
  41729. }
  41730. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41731. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41732. return false;
  41733. }
  41734. else {
  41735. defines._needNormals = true;
  41736. defines.REFLECTION = true;
  41737. defines.ROUGHNESS = (this._roughness > 0);
  41738. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41739. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41740. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41741. switch (this._reflectionTexture.coordinatesMode) {
  41742. case BABYLON.Texture.EXPLICIT_MODE:
  41743. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41744. break;
  41745. case BABYLON.Texture.PLANAR_MODE:
  41746. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41747. break;
  41748. case BABYLON.Texture.PROJECTION_MODE:
  41749. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41750. break;
  41751. case BABYLON.Texture.SKYBOX_MODE:
  41752. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41753. break;
  41754. case BABYLON.Texture.SPHERICAL_MODE:
  41755. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41756. break;
  41757. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41758. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41759. break;
  41760. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41761. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41762. break;
  41763. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41764. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41765. break;
  41766. case BABYLON.Texture.CUBIC_MODE:
  41767. case BABYLON.Texture.INVCUBIC_MODE:
  41768. default:
  41769. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41770. break;
  41771. }
  41772. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41773. }
  41774. }
  41775. else {
  41776. defines.REFLECTION = false;
  41777. }
  41778. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41779. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41780. return false;
  41781. }
  41782. else {
  41783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41784. }
  41785. }
  41786. else {
  41787. defines.EMISSIVE = false;
  41788. }
  41789. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41790. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41791. return false;
  41792. }
  41793. else {
  41794. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41795. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41796. }
  41797. }
  41798. else {
  41799. defines.LIGHTMAP = false;
  41800. }
  41801. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41802. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41803. return false;
  41804. }
  41805. else {
  41806. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41807. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41808. }
  41809. }
  41810. else {
  41811. defines.SPECULAR = false;
  41812. }
  41813. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41814. // Bump texure can not be not blocking.
  41815. if (!this._bumpTexture.isReady()) {
  41816. return false;
  41817. }
  41818. else {
  41819. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41820. defines.PARALLAX = this._useParallax;
  41821. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41822. }
  41823. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41824. }
  41825. else {
  41826. defines.BUMP = false;
  41827. }
  41828. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41829. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41830. return false;
  41831. }
  41832. else {
  41833. defines._needUVs = true;
  41834. defines.REFRACTION = true;
  41835. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41836. }
  41837. }
  41838. else {
  41839. defines.REFRACTION = false;
  41840. }
  41841. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41842. }
  41843. else {
  41844. defines.DIFFUSE = false;
  41845. defines.AMBIENT = false;
  41846. defines.OPACITY = false;
  41847. defines.REFLECTION = false;
  41848. defines.EMISSIVE = false;
  41849. defines.LIGHTMAP = false;
  41850. defines.BUMP = false;
  41851. defines.REFRACTION = false;
  41852. }
  41853. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41854. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41855. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41856. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41857. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41858. }
  41859. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41860. if (!this._imageProcessingConfiguration.isReady()) {
  41861. return false;
  41862. }
  41863. this._imageProcessingConfiguration.prepareDefines(defines);
  41864. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41865. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41866. }
  41867. if (defines._areFresnelDirty) {
  41868. if (StandardMaterial.FresnelEnabled) {
  41869. // Fresnel
  41870. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41871. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41872. this._reflectionFresnelParameters) {
  41873. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41874. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41875. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41876. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41877. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41878. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41879. defines._needNormals = true;
  41880. defines.FRESNEL = true;
  41881. }
  41882. }
  41883. else {
  41884. defines.FRESNEL = false;
  41885. }
  41886. }
  41887. // Misc.
  41888. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41889. // Attribs
  41890. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41891. // Values that need to be evaluated on every frame
  41892. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41893. // Get correct effect
  41894. if (defines.isDirty) {
  41895. defines.markAsProcessed();
  41896. scene.resetCachedMaterial();
  41897. // Fallbacks
  41898. var fallbacks = new BABYLON.EffectFallbacks();
  41899. if (defines.REFLECTION) {
  41900. fallbacks.addFallback(0, "REFLECTION");
  41901. }
  41902. if (defines.SPECULAR) {
  41903. fallbacks.addFallback(0, "SPECULAR");
  41904. }
  41905. if (defines.BUMP) {
  41906. fallbacks.addFallback(0, "BUMP");
  41907. }
  41908. if (defines.PARALLAX) {
  41909. fallbacks.addFallback(1, "PARALLAX");
  41910. }
  41911. if (defines.PARALLAXOCCLUSION) {
  41912. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41913. }
  41914. if (defines.SPECULAROVERALPHA) {
  41915. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41916. }
  41917. if (defines.FOG) {
  41918. fallbacks.addFallback(1, "FOG");
  41919. }
  41920. if (defines.POINTSIZE) {
  41921. fallbacks.addFallback(0, "POINTSIZE");
  41922. }
  41923. if (defines.LOGARITHMICDEPTH) {
  41924. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41925. }
  41926. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41927. if (defines.SPECULARTERM) {
  41928. fallbacks.addFallback(0, "SPECULARTERM");
  41929. }
  41930. if (defines.DIFFUSEFRESNEL) {
  41931. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41932. }
  41933. if (defines.OPACITYFRESNEL) {
  41934. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41935. }
  41936. if (defines.REFLECTIONFRESNEL) {
  41937. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41938. }
  41939. if (defines.EMISSIVEFRESNEL) {
  41940. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41941. }
  41942. if (defines.FRESNEL) {
  41943. fallbacks.addFallback(4, "FRESNEL");
  41944. }
  41945. //Attributes
  41946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41947. if (defines.NORMAL) {
  41948. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41949. }
  41950. if (defines.UV1) {
  41951. attribs.push(BABYLON.VertexBuffer.UVKind);
  41952. }
  41953. if (defines.UV2) {
  41954. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41955. }
  41956. if (defines.VERTEXCOLOR) {
  41957. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41958. }
  41959. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41960. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41961. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41962. var shaderName = "default";
  41963. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41964. "vFogInfos", "vFogColor", "pointSize",
  41965. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41966. "mBones",
  41967. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41968. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41969. "vReflectionPosition", "vReflectionSize",
  41970. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41971. ];
  41972. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41973. var uniformBuffers = ["Material", "Scene"];
  41974. if (BABYLON.ImageProcessingConfiguration) {
  41975. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41976. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41977. }
  41978. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41979. uniformsNames: uniforms,
  41980. uniformBuffersNames: uniformBuffers,
  41981. samplers: samplers,
  41982. defines: defines,
  41983. maxSimultaneousLights: this._maxSimultaneousLights
  41984. });
  41985. if (this.customShaderNameResolve) {
  41986. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41987. }
  41988. var join = defines.toString();
  41989. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41990. attributes: attribs,
  41991. uniformsNames: uniforms,
  41992. uniformBuffersNames: uniformBuffers,
  41993. samplers: samplers,
  41994. defines: join,
  41995. fallbacks: fallbacks,
  41996. onCompiled: this.onCompiled,
  41997. onError: this.onError,
  41998. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41999. }, engine), defines);
  42000. this.buildUniformLayout();
  42001. }
  42002. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42003. return false;
  42004. }
  42005. defines._renderId = scene.getRenderId();
  42006. this._wasPreviouslyReady = true;
  42007. return true;
  42008. };
  42009. StandardMaterial.prototype.buildUniformLayout = function () {
  42010. // Order is important !
  42011. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42012. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42013. this._uniformBuffer.addUniform("opacityParts", 4);
  42014. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42015. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42016. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42017. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42018. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42019. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42020. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42021. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42022. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42023. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42024. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42025. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42026. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42027. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42028. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42029. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42030. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42031. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42032. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42033. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42034. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42035. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42036. this._uniformBuffer.addUniform("specularMatrix", 16);
  42037. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42038. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42039. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42040. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42041. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42042. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42043. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42044. this._uniformBuffer.addUniform("pointSize", 1);
  42045. this._uniformBuffer.create();
  42046. };
  42047. StandardMaterial.prototype.unbind = function () {
  42048. if (this._activeEffect) {
  42049. var needFlag = false;
  42050. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42051. this._activeEffect.setTexture("reflection2DSampler", null);
  42052. needFlag = true;
  42053. }
  42054. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42055. this._activeEffect.setTexture("refraction2DSampler", null);
  42056. needFlag = true;
  42057. }
  42058. if (needFlag) {
  42059. this._markAllSubMeshesAsTexturesDirty();
  42060. }
  42061. }
  42062. _super.prototype.unbind.call(this);
  42063. };
  42064. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42065. var scene = this.getScene();
  42066. var defines = subMesh._materialDefines;
  42067. if (!defines) {
  42068. return;
  42069. }
  42070. var effect = subMesh.effect;
  42071. if (!effect) {
  42072. return;
  42073. }
  42074. this._activeEffect = effect;
  42075. // Matrices
  42076. this.bindOnlyWorldMatrix(world);
  42077. // Normal Matrix
  42078. if (defines.OBJECTSPACE_NORMALMAP) {
  42079. world.toNormalMatrix(this._normalMatrix);
  42080. this.bindOnlyNormalMatrix(this._normalMatrix);
  42081. }
  42082. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42083. // Bones
  42084. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42085. if (mustRebind) {
  42086. this._uniformBuffer.bindToEffect(effect, "Material");
  42087. this.bindViewProjection(effect);
  42088. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42089. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42090. // Fresnel
  42091. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42092. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42093. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42094. }
  42095. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42096. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42097. }
  42098. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42099. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42100. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42101. }
  42102. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42103. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42104. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42105. }
  42106. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42107. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42108. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42109. }
  42110. }
  42111. // Textures
  42112. if (scene.texturesEnabled) {
  42113. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42114. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42115. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42116. if (this._diffuseTexture.hasAlpha) {
  42117. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42118. }
  42119. }
  42120. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42121. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42122. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42123. }
  42124. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42125. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42126. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42127. }
  42128. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42129. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42130. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42131. if (this._reflectionTexture.boundingBoxSize) {
  42132. var cubeTexture = this._reflectionTexture;
  42133. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42134. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42135. }
  42136. }
  42137. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42138. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42139. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42140. }
  42141. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42142. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42143. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42144. }
  42145. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42146. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42147. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42148. }
  42149. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42150. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42151. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42152. if (scene._mirroredCameraPosition) {
  42153. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42154. }
  42155. else {
  42156. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42157. }
  42158. }
  42159. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42160. var depth = 1.0;
  42161. if (!this._refractionTexture.isCube) {
  42162. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42163. if (this._refractionTexture.depth) {
  42164. depth = this._refractionTexture.depth;
  42165. }
  42166. }
  42167. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42168. }
  42169. }
  42170. // Point size
  42171. if (this.pointsCloud) {
  42172. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42173. }
  42174. if (defines.SPECULARTERM) {
  42175. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42176. }
  42177. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42178. // Diffuse
  42179. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42180. }
  42181. // Textures
  42182. if (scene.texturesEnabled) {
  42183. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42184. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42185. }
  42186. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42187. effect.setTexture("ambientSampler", this._ambientTexture);
  42188. }
  42189. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42190. effect.setTexture("opacitySampler", this._opacityTexture);
  42191. }
  42192. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42193. if (this._reflectionTexture.isCube) {
  42194. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42195. }
  42196. else {
  42197. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42198. }
  42199. }
  42200. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42201. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42202. }
  42203. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42204. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42205. }
  42206. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42207. effect.setTexture("specularSampler", this._specularTexture);
  42208. }
  42209. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42210. effect.setTexture("bumpSampler", this._bumpTexture);
  42211. }
  42212. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42213. var depth = 1.0;
  42214. if (this._refractionTexture.isCube) {
  42215. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42216. }
  42217. else {
  42218. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42219. }
  42220. }
  42221. }
  42222. // Clip plane
  42223. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42224. // Colors
  42225. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42226. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42227. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42228. }
  42229. if (mustRebind || !this.isFrozen) {
  42230. // Lights
  42231. if (scene.lightsEnabled && !this._disableLighting) {
  42232. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42233. }
  42234. // View
  42235. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42236. this.bindView(effect);
  42237. }
  42238. // Fog
  42239. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42240. // Morph targets
  42241. if (defines.NUM_MORPH_INFLUENCERS) {
  42242. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42243. }
  42244. // Log. depth
  42245. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42246. // image processing
  42247. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42248. this._imageProcessingConfiguration.bind(this._activeEffect);
  42249. }
  42250. }
  42251. this._uniformBuffer.update();
  42252. this._afterBind(mesh, this._activeEffect);
  42253. };
  42254. StandardMaterial.prototype.getAnimatables = function () {
  42255. var results = [];
  42256. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42257. results.push(this._diffuseTexture);
  42258. }
  42259. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42260. results.push(this._ambientTexture);
  42261. }
  42262. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42263. results.push(this._opacityTexture);
  42264. }
  42265. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42266. results.push(this._reflectionTexture);
  42267. }
  42268. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42269. results.push(this._emissiveTexture);
  42270. }
  42271. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42272. results.push(this._specularTexture);
  42273. }
  42274. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42275. results.push(this._bumpTexture);
  42276. }
  42277. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42278. results.push(this._lightmapTexture);
  42279. }
  42280. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42281. results.push(this._refractionTexture);
  42282. }
  42283. return results;
  42284. };
  42285. StandardMaterial.prototype.getActiveTextures = function () {
  42286. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42287. if (this._diffuseTexture) {
  42288. activeTextures.push(this._diffuseTexture);
  42289. }
  42290. if (this._ambientTexture) {
  42291. activeTextures.push(this._ambientTexture);
  42292. }
  42293. if (this._opacityTexture) {
  42294. activeTextures.push(this._opacityTexture);
  42295. }
  42296. if (this._reflectionTexture) {
  42297. activeTextures.push(this._reflectionTexture);
  42298. }
  42299. if (this._emissiveTexture) {
  42300. activeTextures.push(this._emissiveTexture);
  42301. }
  42302. if (this._specularTexture) {
  42303. activeTextures.push(this._specularTexture);
  42304. }
  42305. if (this._bumpTexture) {
  42306. activeTextures.push(this._bumpTexture);
  42307. }
  42308. if (this._lightmapTexture) {
  42309. activeTextures.push(this._lightmapTexture);
  42310. }
  42311. if (this._refractionTexture) {
  42312. activeTextures.push(this._refractionTexture);
  42313. }
  42314. return activeTextures;
  42315. };
  42316. StandardMaterial.prototype.hasTexture = function (texture) {
  42317. if (_super.prototype.hasTexture.call(this, texture)) {
  42318. return true;
  42319. }
  42320. if (this._diffuseTexture === texture) {
  42321. return true;
  42322. }
  42323. if (this._ambientTexture === texture) {
  42324. return true;
  42325. }
  42326. if (this._opacityTexture === texture) {
  42327. return true;
  42328. }
  42329. if (this._reflectionTexture === texture) {
  42330. return true;
  42331. }
  42332. if (this._emissiveTexture === texture) {
  42333. return true;
  42334. }
  42335. if (this._specularTexture === texture) {
  42336. return true;
  42337. }
  42338. if (this._bumpTexture === texture) {
  42339. return true;
  42340. }
  42341. if (this._lightmapTexture === texture) {
  42342. return true;
  42343. }
  42344. if (this._refractionTexture === texture) {
  42345. return true;
  42346. }
  42347. return false;
  42348. };
  42349. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42350. if (forceDisposeTextures) {
  42351. if (this._diffuseTexture) {
  42352. this._diffuseTexture.dispose();
  42353. }
  42354. if (this._ambientTexture) {
  42355. this._ambientTexture.dispose();
  42356. }
  42357. if (this._opacityTexture) {
  42358. this._opacityTexture.dispose();
  42359. }
  42360. if (this._reflectionTexture) {
  42361. this._reflectionTexture.dispose();
  42362. }
  42363. if (this._emissiveTexture) {
  42364. this._emissiveTexture.dispose();
  42365. }
  42366. if (this._specularTexture) {
  42367. this._specularTexture.dispose();
  42368. }
  42369. if (this._bumpTexture) {
  42370. this._bumpTexture.dispose();
  42371. }
  42372. if (this._lightmapTexture) {
  42373. this._lightmapTexture.dispose();
  42374. }
  42375. if (this._refractionTexture) {
  42376. this._refractionTexture.dispose();
  42377. }
  42378. }
  42379. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42380. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42381. }
  42382. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42383. };
  42384. StandardMaterial.prototype.clone = function (name) {
  42385. var _this = this;
  42386. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42387. result.name = name;
  42388. result.id = name;
  42389. return result;
  42390. };
  42391. StandardMaterial.prototype.serialize = function () {
  42392. return BABYLON.SerializationHelper.Serialize(this);
  42393. };
  42394. // Statics
  42395. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42396. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42397. };
  42398. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42399. get: function () {
  42400. return StandardMaterial._DiffuseTextureEnabled;
  42401. },
  42402. set: function (value) {
  42403. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42404. return;
  42405. }
  42406. StandardMaterial._DiffuseTextureEnabled = value;
  42407. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42408. },
  42409. enumerable: true,
  42410. configurable: true
  42411. });
  42412. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42413. get: function () {
  42414. return StandardMaterial._AmbientTextureEnabled;
  42415. },
  42416. set: function (value) {
  42417. if (StandardMaterial._AmbientTextureEnabled === value) {
  42418. return;
  42419. }
  42420. StandardMaterial._AmbientTextureEnabled = value;
  42421. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42422. },
  42423. enumerable: true,
  42424. configurable: true
  42425. });
  42426. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42427. get: function () {
  42428. return StandardMaterial._OpacityTextureEnabled;
  42429. },
  42430. set: function (value) {
  42431. if (StandardMaterial._OpacityTextureEnabled === value) {
  42432. return;
  42433. }
  42434. StandardMaterial._OpacityTextureEnabled = value;
  42435. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42436. },
  42437. enumerable: true,
  42438. configurable: true
  42439. });
  42440. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42441. get: function () {
  42442. return StandardMaterial._ReflectionTextureEnabled;
  42443. },
  42444. set: function (value) {
  42445. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42446. return;
  42447. }
  42448. StandardMaterial._ReflectionTextureEnabled = value;
  42449. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42455. get: function () {
  42456. return StandardMaterial._EmissiveTextureEnabled;
  42457. },
  42458. set: function (value) {
  42459. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42460. return;
  42461. }
  42462. StandardMaterial._EmissiveTextureEnabled = value;
  42463. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42464. },
  42465. enumerable: true,
  42466. configurable: true
  42467. });
  42468. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42469. get: function () {
  42470. return StandardMaterial._SpecularTextureEnabled;
  42471. },
  42472. set: function (value) {
  42473. if (StandardMaterial._SpecularTextureEnabled === value) {
  42474. return;
  42475. }
  42476. StandardMaterial._SpecularTextureEnabled = value;
  42477. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42478. },
  42479. enumerable: true,
  42480. configurable: true
  42481. });
  42482. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42483. get: function () {
  42484. return StandardMaterial._BumpTextureEnabled;
  42485. },
  42486. set: function (value) {
  42487. if (StandardMaterial._BumpTextureEnabled === value) {
  42488. return;
  42489. }
  42490. StandardMaterial._BumpTextureEnabled = value;
  42491. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42492. },
  42493. enumerable: true,
  42494. configurable: true
  42495. });
  42496. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42497. get: function () {
  42498. return StandardMaterial._LightmapTextureEnabled;
  42499. },
  42500. set: function (value) {
  42501. if (StandardMaterial._LightmapTextureEnabled === value) {
  42502. return;
  42503. }
  42504. StandardMaterial._LightmapTextureEnabled = value;
  42505. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42511. get: function () {
  42512. return StandardMaterial._RefractionTextureEnabled;
  42513. },
  42514. set: function (value) {
  42515. if (StandardMaterial._RefractionTextureEnabled === value) {
  42516. return;
  42517. }
  42518. StandardMaterial._RefractionTextureEnabled = value;
  42519. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42520. },
  42521. enumerable: true,
  42522. configurable: true
  42523. });
  42524. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42525. get: function () {
  42526. return StandardMaterial._ColorGradingTextureEnabled;
  42527. },
  42528. set: function (value) {
  42529. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42530. return;
  42531. }
  42532. StandardMaterial._ColorGradingTextureEnabled = value;
  42533. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42539. get: function () {
  42540. return StandardMaterial._FresnelEnabled;
  42541. },
  42542. set: function (value) {
  42543. if (StandardMaterial._FresnelEnabled === value) {
  42544. return;
  42545. }
  42546. StandardMaterial._FresnelEnabled = value;
  42547. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42548. },
  42549. enumerable: true,
  42550. configurable: true
  42551. });
  42552. // Flags used to enable or disable a type of texture for all Standard Materials
  42553. StandardMaterial._DiffuseTextureEnabled = true;
  42554. StandardMaterial._AmbientTextureEnabled = true;
  42555. StandardMaterial._OpacityTextureEnabled = true;
  42556. StandardMaterial._ReflectionTextureEnabled = true;
  42557. StandardMaterial._EmissiveTextureEnabled = true;
  42558. StandardMaterial._SpecularTextureEnabled = true;
  42559. StandardMaterial._BumpTextureEnabled = true;
  42560. StandardMaterial._LightmapTextureEnabled = true;
  42561. StandardMaterial._RefractionTextureEnabled = true;
  42562. StandardMaterial._ColorGradingTextureEnabled = true;
  42563. StandardMaterial._FresnelEnabled = true;
  42564. __decorate([
  42565. BABYLON.serializeAsTexture("diffuseTexture")
  42566. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42567. __decorate([
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42569. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42570. __decorate([
  42571. BABYLON.serializeAsTexture("ambientTexture")
  42572. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42573. __decorate([
  42574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42575. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42576. __decorate([
  42577. BABYLON.serializeAsTexture("opacityTexture")
  42578. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42579. __decorate([
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42581. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42582. __decorate([
  42583. BABYLON.serializeAsTexture("reflectionTexture")
  42584. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42585. __decorate([
  42586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42587. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42588. __decorate([
  42589. BABYLON.serializeAsTexture("emissiveTexture")
  42590. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42591. __decorate([
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42593. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42594. __decorate([
  42595. BABYLON.serializeAsTexture("specularTexture")
  42596. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42597. __decorate([
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42599. ], StandardMaterial.prototype, "specularTexture", void 0);
  42600. __decorate([
  42601. BABYLON.serializeAsTexture("bumpTexture")
  42602. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42603. __decorate([
  42604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42605. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42606. __decorate([
  42607. BABYLON.serializeAsTexture("lightmapTexture")
  42608. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42609. __decorate([
  42610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42611. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42612. __decorate([
  42613. BABYLON.serializeAsTexture("refractionTexture")
  42614. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42615. __decorate([
  42616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42617. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42618. __decorate([
  42619. BABYLON.serializeAsColor3("ambient")
  42620. ], StandardMaterial.prototype, "ambientColor", void 0);
  42621. __decorate([
  42622. BABYLON.serializeAsColor3("diffuse")
  42623. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42624. __decorate([
  42625. BABYLON.serializeAsColor3("specular")
  42626. ], StandardMaterial.prototype, "specularColor", void 0);
  42627. __decorate([
  42628. BABYLON.serializeAsColor3("emissive")
  42629. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42630. __decorate([
  42631. BABYLON.serialize()
  42632. ], StandardMaterial.prototype, "specularPower", void 0);
  42633. __decorate([
  42634. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42635. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42636. __decorate([
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42638. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42639. __decorate([
  42640. BABYLON.serialize("useEmissiveAsIllumination")
  42641. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42642. __decorate([
  42643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42644. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42645. __decorate([
  42646. BABYLON.serialize("linkEmissiveWithDiffuse")
  42647. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42648. __decorate([
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42651. __decorate([
  42652. BABYLON.serialize("useSpecularOverAlpha")
  42653. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42654. __decorate([
  42655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42656. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42657. __decorate([
  42658. BABYLON.serialize("useReflectionOverAlpha")
  42659. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42660. __decorate([
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42663. __decorate([
  42664. BABYLON.serialize("disableLighting")
  42665. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42666. __decorate([
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42668. ], StandardMaterial.prototype, "disableLighting", void 0);
  42669. __decorate([
  42670. BABYLON.serialize("useObjectSpaceNormalMap")
  42671. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42672. __decorate([
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42675. __decorate([
  42676. BABYLON.serialize("useParallax")
  42677. ], StandardMaterial.prototype, "_useParallax", void 0);
  42678. __decorate([
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], StandardMaterial.prototype, "useParallax", void 0);
  42681. __decorate([
  42682. BABYLON.serialize("useParallaxOcclusion")
  42683. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42684. __decorate([
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42687. __decorate([
  42688. BABYLON.serialize()
  42689. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42690. __decorate([
  42691. BABYLON.serialize("roughness")
  42692. ], StandardMaterial.prototype, "_roughness", void 0);
  42693. __decorate([
  42694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42695. ], StandardMaterial.prototype, "roughness", void 0);
  42696. __decorate([
  42697. BABYLON.serialize()
  42698. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42699. __decorate([
  42700. BABYLON.serialize()
  42701. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42702. __decorate([
  42703. BABYLON.serialize()
  42704. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42705. __decorate([
  42706. BABYLON.serialize("useLightmapAsShadowmap")
  42707. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42708. __decorate([
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42711. __decorate([
  42712. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42713. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42714. __decorate([
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42716. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42717. __decorate([
  42718. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42719. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42720. __decorate([
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42722. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42723. __decorate([
  42724. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42725. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42726. __decorate([
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42728. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42729. __decorate([
  42730. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42731. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42732. __decorate([
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42734. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42735. __decorate([
  42736. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42737. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42738. __decorate([
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42740. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42741. __decorate([
  42742. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42743. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42744. __decorate([
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42746. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42747. __decorate([
  42748. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42749. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42750. __decorate([
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42752. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42753. __decorate([
  42754. BABYLON.serialize("maxSimultaneousLights")
  42755. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42756. __decorate([
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42758. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42759. __decorate([
  42760. BABYLON.serialize("invertNormalMapX")
  42761. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42762. __decorate([
  42763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42764. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42765. __decorate([
  42766. BABYLON.serialize("invertNormalMapY")
  42767. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42768. __decorate([
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42771. __decorate([
  42772. BABYLON.serialize("twoSidedLighting")
  42773. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42774. __decorate([
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42776. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42777. __decorate([
  42778. BABYLON.serialize()
  42779. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42780. return StandardMaterial;
  42781. }(BABYLON.PushMaterial));
  42782. BABYLON.StandardMaterial = StandardMaterial;
  42783. })(BABYLON || (BABYLON = {}));
  42784. //# sourceMappingURL=babylon.standardMaterial.js.map
  42785. var BABYLON;
  42786. (function (BABYLON) {
  42787. /**
  42788. * Manages the defines for the PBR Material.
  42789. * @hiddenChildren
  42790. */
  42791. var PBRMaterialDefines = /** @class */ (function (_super) {
  42792. __extends(PBRMaterialDefines, _super);
  42793. /**
  42794. * Initializes the PBR Material defines.
  42795. */
  42796. function PBRMaterialDefines() {
  42797. var _this = _super.call(this) || this;
  42798. _this.PBR = true;
  42799. _this.MAINUV1 = false;
  42800. _this.MAINUV2 = false;
  42801. _this.UV1 = false;
  42802. _this.UV2 = false;
  42803. _this.ALBEDO = false;
  42804. _this.ALBEDODIRECTUV = 0;
  42805. _this.VERTEXCOLOR = false;
  42806. _this.AMBIENT = false;
  42807. _this.AMBIENTDIRECTUV = 0;
  42808. _this.AMBIENTINGRAYSCALE = false;
  42809. _this.OPACITY = false;
  42810. _this.VERTEXALPHA = false;
  42811. _this.OPACITYDIRECTUV = 0;
  42812. _this.OPACITYRGB = false;
  42813. _this.ALPHATEST = false;
  42814. _this.DEPTHPREPASS = false;
  42815. _this.ALPHABLEND = false;
  42816. _this.ALPHAFROMALBEDO = false;
  42817. _this.ALPHATESTVALUE = "0.5";
  42818. _this.SPECULAROVERALPHA = false;
  42819. _this.RADIANCEOVERALPHA = false;
  42820. _this.ALPHAFRESNEL = false;
  42821. _this.LINEARALPHAFRESNEL = false;
  42822. _this.PREMULTIPLYALPHA = false;
  42823. _this.EMISSIVE = false;
  42824. _this.EMISSIVEDIRECTUV = 0;
  42825. _this.REFLECTIVITY = false;
  42826. _this.REFLECTIVITYDIRECTUV = 0;
  42827. _this.SPECULARTERM = false;
  42828. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  42829. _this.MICROSURFACEAUTOMATIC = false;
  42830. _this.LODBASEDMICROSFURACE = false;
  42831. _this.MICROSURFACEMAP = false;
  42832. _this.MICROSURFACEMAPDIRECTUV = 0;
  42833. _this.METALLICWORKFLOW = false;
  42834. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  42835. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  42836. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  42837. _this.AOSTOREINMETALMAPRED = false;
  42838. _this.ENVIRONMENTBRDF = false;
  42839. _this.NORMAL = false;
  42840. _this.TANGENT = false;
  42841. _this.BUMP = false;
  42842. _this.BUMPDIRECTUV = 0;
  42843. _this.OBJECTSPACE_NORMALMAP = false;
  42844. _this.PARALLAX = false;
  42845. _this.PARALLAXOCCLUSION = false;
  42846. _this.NORMALXYSCALE = true;
  42847. _this.LIGHTMAP = false;
  42848. _this.LIGHTMAPDIRECTUV = 0;
  42849. _this.USELIGHTMAPASSHADOWMAP = false;
  42850. _this.GAMMALIGHTMAP = false;
  42851. _this.REFLECTION = false;
  42852. _this.REFLECTIONMAP_3D = false;
  42853. _this.REFLECTIONMAP_SPHERICAL = false;
  42854. _this.REFLECTIONMAP_PLANAR = false;
  42855. _this.REFLECTIONMAP_CUBIC = false;
  42856. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42857. _this.REFLECTIONMAP_PROJECTION = false;
  42858. _this.REFLECTIONMAP_SKYBOX = false;
  42859. _this.REFLECTIONMAP_EXPLICIT = false;
  42860. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42861. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42862. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42863. _this.INVERTCUBICMAP = false;
  42864. _this.USESPHERICALFROMREFLECTIONMAP = false;
  42865. _this.USESPHERICALINVERTEX = false;
  42866. _this.REFLECTIONMAP_OPPOSITEZ = false;
  42867. _this.LODINREFLECTIONALPHA = false;
  42868. _this.GAMMAREFLECTION = false;
  42869. _this.RGBDREFLECTION = false;
  42870. _this.RADIANCEOCCLUSION = false;
  42871. _this.HORIZONOCCLUSION = false;
  42872. _this.REFRACTION = false;
  42873. _this.REFRACTIONMAP_3D = false;
  42874. _this.REFRACTIONMAP_OPPOSITEZ = false;
  42875. _this.LODINREFRACTIONALPHA = false;
  42876. _this.GAMMAREFRACTION = false;
  42877. _this.RGBDREFRACTION = false;
  42878. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  42879. _this.INSTANCES = false;
  42880. _this.NUM_BONE_INFLUENCERS = 0;
  42881. _this.BonesPerMesh = 0;
  42882. _this.NONUNIFORMSCALING = false;
  42883. _this.MORPHTARGETS = false;
  42884. _this.MORPHTARGETS_NORMAL = false;
  42885. _this.MORPHTARGETS_TANGENT = false;
  42886. _this.NUM_MORPH_INFLUENCERS = 0;
  42887. _this.IMAGEPROCESSING = false;
  42888. _this.VIGNETTE = false;
  42889. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42890. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42891. _this.TONEMAPPING = false;
  42892. _this.CONTRAST = false;
  42893. _this.COLORCURVES = false;
  42894. _this.COLORGRADING = false;
  42895. _this.COLORGRADING3D = false;
  42896. _this.SAMPLER3DGREENDEPTH = false;
  42897. _this.SAMPLER3DBGRMAP = false;
  42898. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42899. _this.EXPOSURE = false;
  42900. _this.USEPHYSICALLIGHTFALLOFF = false;
  42901. _this.TWOSIDEDLIGHTING = false;
  42902. _this.SHADOWFLOAT = false;
  42903. _this.CLIPPLANE = false;
  42904. _this.POINTSIZE = false;
  42905. _this.FOG = false;
  42906. _this.LOGARITHMICDEPTH = false;
  42907. _this.FORCENORMALFORWARD = false;
  42908. _this.SPECULARAA = false;
  42909. _this.UNLIT = false;
  42910. _this.rebuild();
  42911. return _this;
  42912. }
  42913. /**
  42914. * Resets the PBR Material defines.
  42915. */
  42916. PBRMaterialDefines.prototype.reset = function () {
  42917. _super.prototype.reset.call(this);
  42918. this.ALPHATESTVALUE = "0.5";
  42919. this.PBR = true;
  42920. };
  42921. return PBRMaterialDefines;
  42922. }(BABYLON.MaterialDefines));
  42923. /**
  42924. * The Physically based material base class of BJS.
  42925. *
  42926. * This offers the main features of a standard PBR material.
  42927. * For more information, please refer to the documentation :
  42928. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42929. */
  42930. var PBRBaseMaterial = /** @class */ (function (_super) {
  42931. __extends(PBRBaseMaterial, _super);
  42932. /**
  42933. * Instantiates a new PBRMaterial instance.
  42934. *
  42935. * @param name The material name
  42936. * @param scene The scene the material will be use in.
  42937. */
  42938. function PBRBaseMaterial(name, scene) {
  42939. var _this = _super.call(this, name, scene) || this;
  42940. /**
  42941. * Intensity of the direct lights e.g. the four lights available in your scene.
  42942. * This impacts both the direct diffuse and specular highlights.
  42943. */
  42944. _this._directIntensity = 1.0;
  42945. /**
  42946. * Intensity of the emissive part of the material.
  42947. * This helps controlling the emissive effect without modifying the emissive color.
  42948. */
  42949. _this._emissiveIntensity = 1.0;
  42950. /**
  42951. * Intensity of the environment e.g. how much the environment will light the object
  42952. * either through harmonics for rough material or through the refelction for shiny ones.
  42953. */
  42954. _this._environmentIntensity = 1.0;
  42955. /**
  42956. * This is a special control allowing the reduction of the specular highlights coming from the
  42957. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42958. */
  42959. _this._specularIntensity = 1.0;
  42960. /**
  42961. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  42962. */
  42963. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  42964. /**
  42965. * Debug Control allowing disabling the bump map on this material.
  42966. */
  42967. _this._disableBumpMap = false;
  42968. /**
  42969. * AKA Occlusion Texture Intensity in other nomenclature.
  42970. */
  42971. _this._ambientTextureStrength = 1.0;
  42972. /**
  42973. * The color of a material in ambient lighting.
  42974. */
  42975. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  42976. /**
  42977. * AKA Diffuse Color in other nomenclature.
  42978. */
  42979. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  42980. /**
  42981. * AKA Specular Color in other nomenclature.
  42982. */
  42983. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42984. /**
  42985. * The color applied when light is reflected from a material.
  42986. */
  42987. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  42988. /**
  42989. * The color applied when light is emitted from a material.
  42990. */
  42991. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  42992. /**
  42993. * AKA Glossiness in other nomenclature.
  42994. */
  42995. _this._microSurface = 0.9;
  42996. /**
  42997. * source material index of refraction (IOR)' / 'destination material IOR.
  42998. */
  42999. _this._indexOfRefraction = 0.66;
  43000. /**
  43001. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43002. */
  43003. _this._invertRefractionY = false;
  43004. /**
  43005. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43006. * Materials half opaque for instance using refraction could benefit from this control.
  43007. */
  43008. _this._linkRefractionWithTransparency = false;
  43009. /**
  43010. * Specifies that the material will use the light map as a show map.
  43011. */
  43012. _this._useLightmapAsShadowmap = false;
  43013. /**
  43014. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43015. * makes the reflect vector face the model (under horizon).
  43016. */
  43017. _this._useHorizonOcclusion = true;
  43018. /**
  43019. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43020. * too much the area relying on ambient texture to define their ambient occlusion.
  43021. */
  43022. _this._useRadianceOcclusion = true;
  43023. /**
  43024. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43025. */
  43026. _this._useAlphaFromAlbedoTexture = false;
  43027. /**
  43028. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43029. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43030. */
  43031. _this._useSpecularOverAlpha = true;
  43032. /**
  43033. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43034. */
  43035. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43036. /**
  43037. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43038. */
  43039. _this._useRoughnessFromMetallicTextureAlpha = true;
  43040. /**
  43041. * Specifies if the metallic texture contains the roughness information in its green channel.
  43042. */
  43043. _this._useRoughnessFromMetallicTextureGreen = false;
  43044. /**
  43045. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43046. */
  43047. _this._useMetallnessFromMetallicTextureBlue = false;
  43048. /**
  43049. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43050. */
  43051. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43052. /**
  43053. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43054. */
  43055. _this._useAmbientInGrayScale = false;
  43056. /**
  43057. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43058. * The material will try to infer what glossiness each pixel should be.
  43059. */
  43060. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43061. /**
  43062. * BJS is using an harcoded light falloff based on a manually sets up range.
  43063. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43064. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43065. */
  43066. _this._usePhysicalLightFalloff = true;
  43067. /**
  43068. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43069. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43070. */
  43071. _this._useRadianceOverAlpha = true;
  43072. /**
  43073. * Allows using an object space normal map (instead of tangent space).
  43074. */
  43075. _this._useObjectSpaceNormalMap = false;
  43076. /**
  43077. * Allows using the bump map in parallax mode.
  43078. */
  43079. _this._useParallax = false;
  43080. /**
  43081. * Allows using the bump map in parallax occlusion mode.
  43082. */
  43083. _this._useParallaxOcclusion = false;
  43084. /**
  43085. * Controls the scale bias of the parallax mode.
  43086. */
  43087. _this._parallaxScaleBias = 0.05;
  43088. /**
  43089. * If sets to true, disables all the lights affecting the material.
  43090. */
  43091. _this._disableLighting = false;
  43092. /**
  43093. * Number of Simultaneous lights allowed on the material.
  43094. */
  43095. _this._maxSimultaneousLights = 4;
  43096. /**
  43097. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43098. */
  43099. _this._invertNormalMapX = false;
  43100. /**
  43101. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43102. */
  43103. _this._invertNormalMapY = false;
  43104. /**
  43105. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43106. */
  43107. _this._twoSidedLighting = false;
  43108. /**
  43109. * Defines the alpha limits in alpha test mode.
  43110. */
  43111. _this._alphaCutOff = 0.4;
  43112. /**
  43113. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43114. */
  43115. _this._forceAlphaTest = false;
  43116. /**
  43117. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43118. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43119. */
  43120. _this._useAlphaFresnel = false;
  43121. /**
  43122. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43123. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43124. */
  43125. _this._useLinearAlphaFresnel = false;
  43126. /**
  43127. * The transparency mode of the material.
  43128. */
  43129. _this._transparencyMode = null;
  43130. /**
  43131. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43132. * from cos thetav and roughness:
  43133. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43134. */
  43135. _this._environmentBRDFTexture = null;
  43136. /**
  43137. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43138. */
  43139. _this._forceIrradianceInFragment = false;
  43140. /**
  43141. * Force normal to face away from face.
  43142. */
  43143. _this._forceNormalForward = false;
  43144. /**
  43145. * Enables specular anti aliasing in the PBR shader.
  43146. * It will both interacts on the Geometry for analytical and IBL lighting.
  43147. * It also prefilter the roughness map based on the bump values.
  43148. */
  43149. _this._enableSpecularAntiAliasing = false;
  43150. /**
  43151. * Stores the available render targets.
  43152. */
  43153. _this._renderTargets = new BABYLON.SmartArray(16);
  43154. /**
  43155. * Sets the global ambient color for the material used in lighting calculations.
  43156. */
  43157. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43158. /**
  43159. * If set to true, no lighting calculations will be applied.
  43160. */
  43161. _this._unlit = false;
  43162. // Setup the default processing configuration to the scene.
  43163. _this._attachImageProcessingConfiguration(null);
  43164. _this.getRenderTargetTextures = function () {
  43165. _this._renderTargets.reset();
  43166. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43167. _this._renderTargets.push(_this._reflectionTexture);
  43168. }
  43169. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43170. _this._renderTargets.push(_this._refractionTexture);
  43171. }
  43172. return _this._renderTargets;
  43173. };
  43174. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43175. return _this;
  43176. }
  43177. /**
  43178. * Attaches a new image processing configuration to the PBR Material.
  43179. * @param configuration
  43180. */
  43181. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43182. var _this = this;
  43183. if (configuration === this._imageProcessingConfiguration) {
  43184. return;
  43185. }
  43186. // Detaches observer.
  43187. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43188. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43189. }
  43190. // Pick the scene configuration if needed.
  43191. if (!configuration) {
  43192. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43193. }
  43194. else {
  43195. this._imageProcessingConfiguration = configuration;
  43196. }
  43197. // Attaches observer.
  43198. if (this._imageProcessingConfiguration) {
  43199. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43200. _this._markAllSubMeshesAsImageProcessingDirty();
  43201. });
  43202. }
  43203. };
  43204. /**
  43205. * Gets the name of the material class.
  43206. */
  43207. PBRBaseMaterial.prototype.getClassName = function () {
  43208. return "PBRBaseMaterial";
  43209. };
  43210. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43211. /**
  43212. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43213. */
  43214. get: function () {
  43215. return this._useLogarithmicDepth;
  43216. },
  43217. /**
  43218. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43219. */
  43220. set: function (value) {
  43221. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43222. },
  43223. enumerable: true,
  43224. configurable: true
  43225. });
  43226. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43227. /**
  43228. * Gets the current transparency mode.
  43229. */
  43230. get: function () {
  43231. return this._transparencyMode;
  43232. },
  43233. /**
  43234. * Sets the transparency mode of the material.
  43235. *
  43236. * | Value | Type | Description |
  43237. * | ----- | ----------------------------------- | ----------- |
  43238. * | 0 | OPAQUE | |
  43239. * | 1 | ALPHATEST | |
  43240. * | 2 | ALPHABLEND | |
  43241. * | 3 | ALPHATESTANDBLEND | |
  43242. *
  43243. */
  43244. set: function (value) {
  43245. if (this._transparencyMode === value) {
  43246. return;
  43247. }
  43248. this._transparencyMode = value;
  43249. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43250. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43251. },
  43252. enumerable: true,
  43253. configurable: true
  43254. });
  43255. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43256. /**
  43257. * Returns true if alpha blending should be disabled.
  43258. */
  43259. get: function () {
  43260. return (this._linkRefractionWithTransparency ||
  43261. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43262. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43263. },
  43264. enumerable: true,
  43265. configurable: true
  43266. });
  43267. /**
  43268. * Specifies whether or not this material should be rendered in alpha blend mode.
  43269. */
  43270. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43271. if (this._disableAlphaBlending) {
  43272. return false;
  43273. }
  43274. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43275. };
  43276. /**
  43277. * Specifies if the mesh will require alpha blending.
  43278. * @param mesh - BJS mesh.
  43279. */
  43280. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43281. if (this._disableAlphaBlending) {
  43282. return false;
  43283. }
  43284. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43285. };
  43286. /**
  43287. * Specifies whether or not this material should be rendered in alpha test mode.
  43288. */
  43289. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43290. if (this._forceAlphaTest) {
  43291. return true;
  43292. }
  43293. if (this._linkRefractionWithTransparency) {
  43294. return false;
  43295. }
  43296. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43297. };
  43298. /**
  43299. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43300. */
  43301. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43302. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43303. };
  43304. /**
  43305. * Gets the texture used for the alpha test.
  43306. */
  43307. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43308. return this._albedoTexture;
  43309. };
  43310. /**
  43311. * Specifies that the submesh is ready to be used.
  43312. * @param mesh - BJS mesh.
  43313. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43314. * @param useInstances - Specifies that instances should be used.
  43315. * @returns - boolean indicating that the submesh is ready or not.
  43316. */
  43317. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43318. if (subMesh.effect && this.isFrozen) {
  43319. if (this._wasPreviouslyReady) {
  43320. return true;
  43321. }
  43322. }
  43323. if (!subMesh._materialDefines) {
  43324. subMesh._materialDefines = new PBRMaterialDefines();
  43325. }
  43326. var defines = subMesh._materialDefines;
  43327. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43328. if (defines._renderId === this.getScene().getRenderId()) {
  43329. return true;
  43330. }
  43331. }
  43332. var scene = this.getScene();
  43333. var engine = scene.getEngine();
  43334. if (defines._areTexturesDirty) {
  43335. if (scene.texturesEnabled) {
  43336. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43337. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43338. return false;
  43339. }
  43340. }
  43341. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43342. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43343. return false;
  43344. }
  43345. }
  43346. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43347. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43348. return false;
  43349. }
  43350. }
  43351. var reflectionTexture = this._getReflectionTexture();
  43352. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43353. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43354. return false;
  43355. }
  43356. }
  43357. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43358. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43359. return false;
  43360. }
  43361. }
  43362. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43363. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43364. return false;
  43365. }
  43366. }
  43367. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43368. if (this._metallicTexture) {
  43369. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43370. return false;
  43371. }
  43372. }
  43373. else if (this._reflectivityTexture) {
  43374. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43375. return false;
  43376. }
  43377. }
  43378. if (this._microSurfaceTexture) {
  43379. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43380. return false;
  43381. }
  43382. }
  43383. }
  43384. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43385. // Bump texture cannot be not blocking.
  43386. if (!this._bumpTexture.isReady()) {
  43387. return false;
  43388. }
  43389. }
  43390. var refractionTexture = this._getRefractionTexture();
  43391. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43392. if (!refractionTexture.isReadyOrNotBlocking()) {
  43393. return false;
  43394. }
  43395. }
  43396. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43397. // This is blocking.
  43398. if (!this._environmentBRDFTexture.isReady()) {
  43399. return false;
  43400. }
  43401. }
  43402. }
  43403. }
  43404. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43405. if (!this._imageProcessingConfiguration.isReady()) {
  43406. return false;
  43407. }
  43408. }
  43409. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43410. mesh.createNormals(true);
  43411. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43412. }
  43413. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43414. if (effect) {
  43415. scene.resetCachedMaterial();
  43416. subMesh.setEffect(effect, defines);
  43417. this.buildUniformLayout();
  43418. }
  43419. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43420. return false;
  43421. }
  43422. defines._renderId = scene.getRenderId();
  43423. this._wasPreviouslyReady = true;
  43424. return true;
  43425. };
  43426. /**
  43427. * Specifies if the material uses metallic roughness workflow.
  43428. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43429. */
  43430. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43431. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43432. return true;
  43433. }
  43434. return false;
  43435. };
  43436. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43437. if (onCompiled === void 0) { onCompiled = null; }
  43438. if (onError === void 0) { onError = null; }
  43439. if (useInstances === void 0) { useInstances = null; }
  43440. if (useClipPlane === void 0) { useClipPlane = null; }
  43441. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43442. if (!defines.isDirty) {
  43443. return null;
  43444. }
  43445. defines.markAsProcessed();
  43446. var scene = this.getScene();
  43447. var engine = scene.getEngine();
  43448. // Fallbacks
  43449. var fallbacks = new BABYLON.EffectFallbacks();
  43450. var fallbackRank = 0;
  43451. if (defines.USESPHERICALINVERTEX) {
  43452. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43453. }
  43454. if (defines.FOG) {
  43455. fallbacks.addFallback(fallbackRank, "FOG");
  43456. }
  43457. if (defines.SPECULARAA) {
  43458. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43459. }
  43460. if (defines.POINTSIZE) {
  43461. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43462. }
  43463. if (defines.LOGARITHMICDEPTH) {
  43464. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43465. }
  43466. if (defines.PARALLAX) {
  43467. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43468. }
  43469. if (defines.PARALLAXOCCLUSION) {
  43470. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43471. }
  43472. if (defines.ENVIRONMENTBRDF) {
  43473. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43474. }
  43475. if (defines.TANGENT) {
  43476. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43477. }
  43478. if (defines.BUMP) {
  43479. fallbacks.addFallback(fallbackRank++, "BUMP");
  43480. }
  43481. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43482. if (defines.SPECULARTERM) {
  43483. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43484. }
  43485. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43486. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43487. }
  43488. if (defines.LIGHTMAP) {
  43489. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43490. }
  43491. if (defines.NORMAL) {
  43492. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43493. }
  43494. if (defines.AMBIENT) {
  43495. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43496. }
  43497. if (defines.EMISSIVE) {
  43498. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43499. }
  43500. if (defines.VERTEXCOLOR) {
  43501. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43502. }
  43503. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43504. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43505. }
  43506. if (defines.MORPHTARGETS) {
  43507. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43508. }
  43509. //Attributes
  43510. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43511. if (defines.NORMAL) {
  43512. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43513. }
  43514. if (defines.TANGENT) {
  43515. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43516. }
  43517. if (defines.UV1) {
  43518. attribs.push(BABYLON.VertexBuffer.UVKind);
  43519. }
  43520. if (defines.UV2) {
  43521. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43522. }
  43523. if (defines.VERTEXCOLOR) {
  43524. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43525. }
  43526. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43527. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43528. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43529. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43530. "vFogInfos", "vFogColor", "pointSize",
  43531. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43532. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43533. "mBones",
  43534. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43535. "vLightingIntensity",
  43536. "logarithmicDepthConstant",
  43537. "vSphericalX", "vSphericalY", "vSphericalZ",
  43538. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43539. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43540. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43541. "vTangentSpaceParams"
  43542. ];
  43543. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43544. "bumpSampler", "lightmapSampler", "opacitySampler",
  43545. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43546. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43547. "microSurfaceSampler", "environmentBrdfSampler"];
  43548. var uniformBuffers = ["Material", "Scene"];
  43549. if (BABYLON.ImageProcessingConfiguration) {
  43550. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43551. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43552. }
  43553. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43554. uniformsNames: uniforms,
  43555. uniformBuffersNames: uniformBuffers,
  43556. samplers: samplers,
  43557. defines: defines,
  43558. maxSimultaneousLights: this._maxSimultaneousLights
  43559. });
  43560. var join = defines.toString();
  43561. return engine.createEffect("pbr", {
  43562. attributes: attribs,
  43563. uniformsNames: uniforms,
  43564. uniformBuffersNames: uniformBuffers,
  43565. samplers: samplers,
  43566. defines: join,
  43567. fallbacks: fallbacks,
  43568. onCompiled: onCompiled,
  43569. onError: onError,
  43570. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43571. }, engine);
  43572. };
  43573. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43574. if (useInstances === void 0) { useInstances = null; }
  43575. if (useClipPlane === void 0) { useClipPlane = null; }
  43576. var scene = this.getScene();
  43577. var engine = scene.getEngine();
  43578. // Lights
  43579. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43580. defines._needNormals = true;
  43581. // Textures
  43582. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43583. if (defines._areTexturesDirty) {
  43584. defines._needUVs = false;
  43585. if (scene.texturesEnabled) {
  43586. if (scene.getEngine().getCaps().textureLOD) {
  43587. defines.LODBASEDMICROSFURACE = true;
  43588. }
  43589. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43590. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43591. }
  43592. else {
  43593. defines.ALBEDO = false;
  43594. }
  43595. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43596. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43597. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43598. }
  43599. else {
  43600. defines.AMBIENT = false;
  43601. }
  43602. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43603. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43604. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43605. }
  43606. else {
  43607. defines.OPACITY = false;
  43608. }
  43609. var reflectionTexture = this._getReflectionTexture();
  43610. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43611. defines.REFLECTION = true;
  43612. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43613. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43614. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43615. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43616. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43617. defines.INVERTCUBICMAP = true;
  43618. }
  43619. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43620. switch (reflectionTexture.coordinatesMode) {
  43621. case BABYLON.Texture.EXPLICIT_MODE:
  43622. defines.REFLECTIONMAP_EXPLICIT = true;
  43623. break;
  43624. case BABYLON.Texture.PLANAR_MODE:
  43625. defines.REFLECTIONMAP_PLANAR = true;
  43626. break;
  43627. case BABYLON.Texture.PROJECTION_MODE:
  43628. defines.REFLECTIONMAP_PROJECTION = true;
  43629. break;
  43630. case BABYLON.Texture.SKYBOX_MODE:
  43631. defines.REFLECTIONMAP_SKYBOX = true;
  43632. break;
  43633. case BABYLON.Texture.SPHERICAL_MODE:
  43634. defines.REFLECTIONMAP_SPHERICAL = true;
  43635. break;
  43636. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43637. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43638. break;
  43639. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43640. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43641. break;
  43642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43643. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43644. break;
  43645. case BABYLON.Texture.CUBIC_MODE:
  43646. case BABYLON.Texture.INVCUBIC_MODE:
  43647. default:
  43648. defines.REFLECTIONMAP_CUBIC = true;
  43649. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43650. break;
  43651. }
  43652. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43653. if (reflectionTexture.sphericalPolynomial) {
  43654. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43655. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43656. defines.USESPHERICALINVERTEX = false;
  43657. }
  43658. else {
  43659. defines.USESPHERICALINVERTEX = true;
  43660. }
  43661. }
  43662. }
  43663. }
  43664. else {
  43665. defines.REFLECTION = false;
  43666. defines.REFLECTIONMAP_3D = false;
  43667. defines.REFLECTIONMAP_SPHERICAL = false;
  43668. defines.REFLECTIONMAP_PLANAR = false;
  43669. defines.REFLECTIONMAP_CUBIC = false;
  43670. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43671. defines.REFLECTIONMAP_PROJECTION = false;
  43672. defines.REFLECTIONMAP_SKYBOX = false;
  43673. defines.REFLECTIONMAP_EXPLICIT = false;
  43674. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43675. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43676. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43677. defines.INVERTCUBICMAP = false;
  43678. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43679. defines.USESPHERICALINVERTEX = false;
  43680. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43681. defines.LODINREFLECTIONALPHA = false;
  43682. defines.GAMMAREFLECTION = false;
  43683. defines.RGBDREFLECTION = false;
  43684. }
  43685. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43686. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43687. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43688. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43689. }
  43690. else {
  43691. defines.LIGHTMAP = false;
  43692. }
  43693. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43694. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43695. }
  43696. else {
  43697. defines.EMISSIVE = false;
  43698. }
  43699. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43700. if (this._metallicTexture) {
  43701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43702. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43703. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43704. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43705. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43706. }
  43707. else if (this._reflectivityTexture) {
  43708. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43709. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43710. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43711. }
  43712. else {
  43713. defines.REFLECTIVITY = false;
  43714. }
  43715. if (this._microSurfaceTexture) {
  43716. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43717. }
  43718. else {
  43719. defines.MICROSURFACEMAP = false;
  43720. }
  43721. }
  43722. else {
  43723. defines.REFLECTIVITY = false;
  43724. defines.MICROSURFACEMAP = false;
  43725. }
  43726. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43727. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43728. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43729. defines.PARALLAX = true;
  43730. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43731. }
  43732. else {
  43733. defines.PARALLAX = false;
  43734. }
  43735. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43736. }
  43737. else {
  43738. defines.BUMP = false;
  43739. }
  43740. var refractionTexture = this._getRefractionTexture();
  43741. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43742. defines.REFRACTION = true;
  43743. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43744. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43745. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  43746. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43747. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43748. if (this._linkRefractionWithTransparency) {
  43749. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43750. }
  43751. }
  43752. else {
  43753. defines.REFRACTION = false;
  43754. }
  43755. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43756. defines.ENVIRONMENTBRDF = true;
  43757. }
  43758. else {
  43759. defines.ENVIRONMENTBRDF = false;
  43760. }
  43761. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43762. defines.ALPHAFROMALBEDO = true;
  43763. }
  43764. else {
  43765. defines.ALPHAFROMALBEDO = false;
  43766. }
  43767. }
  43768. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43769. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43770. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43771. if (!this.backFaceCulling && this._twoSidedLighting) {
  43772. defines.TWOSIDEDLIGHTING = true;
  43773. }
  43774. else {
  43775. defines.TWOSIDEDLIGHTING = false;
  43776. }
  43777. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43778. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43779. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43780. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43781. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43782. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43783. }
  43784. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43785. this._imageProcessingConfiguration.prepareDefines(defines);
  43786. }
  43787. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43788. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43789. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43790. // Misc.
  43791. if (defines._areMiscDirty) {
  43792. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43793. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43794. }
  43795. // Values that need to be evaluated on every frame
  43796. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43797. // Attribs
  43798. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43799. };
  43800. /**
  43801. * Force shader compilation
  43802. */
  43803. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43804. var _this = this;
  43805. var localOptions = __assign({ clipPlane: false }, options);
  43806. var defines = new PBRMaterialDefines();
  43807. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43808. if (effect.isReady()) {
  43809. if (onCompiled) {
  43810. onCompiled(this);
  43811. }
  43812. }
  43813. else {
  43814. effect.onCompileObservable.add(function () {
  43815. if (onCompiled) {
  43816. onCompiled(_this);
  43817. }
  43818. });
  43819. }
  43820. };
  43821. /**
  43822. * Initializes the uniform buffer layout for the shader.
  43823. */
  43824. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  43825. // Order is important !
  43826. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  43827. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  43828. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43829. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43830. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43831. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  43832. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  43833. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43834. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43835. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43836. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43837. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43838. this._uniformBuffer.addUniform("albedoMatrix", 16);
  43839. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43840. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43841. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43842. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43843. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  43844. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  43845. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43846. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43847. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43848. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43849. this._uniformBuffer.addUniform("vReflectionColor", 3);
  43850. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  43851. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  43852. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  43853. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  43854. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  43855. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43856. this._uniformBuffer.addUniform("pointSize", 1);
  43857. this._uniformBuffer.create();
  43858. };
  43859. /**
  43860. * Unbinds the textures.
  43861. */
  43862. PBRBaseMaterial.prototype.unbind = function () {
  43863. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43864. this._uniformBuffer.setTexture("reflectionSampler", null);
  43865. }
  43866. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43867. this._uniformBuffer.setTexture("refractionSampler", null);
  43868. }
  43869. _super.prototype.unbind.call(this);
  43870. };
  43871. /**
  43872. * Binds the submesh data.
  43873. * @param world - The world matrix.
  43874. * @param mesh - The BJS mesh.
  43875. * @param subMesh - A submesh of the BJS mesh.
  43876. */
  43877. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43878. var scene = this.getScene();
  43879. var defines = subMesh._materialDefines;
  43880. if (!defines) {
  43881. return;
  43882. }
  43883. var effect = subMesh.effect;
  43884. if (!effect) {
  43885. return;
  43886. }
  43887. this._activeEffect = effect;
  43888. // Matrices
  43889. this.bindOnlyWorldMatrix(world);
  43890. // Normal Matrix
  43891. if (defines.OBJECTSPACE_NORMALMAP) {
  43892. world.toNormalMatrix(this._normalMatrix);
  43893. this.bindOnlyNormalMatrix(this._normalMatrix);
  43894. }
  43895. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43896. // Bones
  43897. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  43898. var reflectionTexture = null;
  43899. if (mustRebind) {
  43900. this._uniformBuffer.bindToEffect(effect, "Material");
  43901. this.bindViewProjection(effect);
  43902. reflectionTexture = this._getReflectionTexture();
  43903. var refractionTexture = this._getRefractionTexture();
  43904. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43905. // Texture uniforms
  43906. if (scene.texturesEnabled) {
  43907. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43908. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  43909. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  43910. }
  43911. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43912. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  43913. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43914. }
  43915. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43916. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43917. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43918. }
  43919. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43920. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  43921. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  43922. if (reflectionTexture.boundingBoxSize) {
  43923. var cubeTexture = reflectionTexture;
  43924. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43925. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43926. }
  43927. var polynomials = reflectionTexture.sphericalPolynomial;
  43928. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  43929. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  43930. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  43931. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  43932. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  43933. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  43934. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  43935. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  43936. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  43937. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  43938. }
  43939. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  43940. }
  43941. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43942. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43943. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43944. }
  43945. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43946. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43947. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43948. }
  43949. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43950. if (this._metallicTexture) {
  43951. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  43952. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  43953. }
  43954. else if (this._reflectivityTexture) {
  43955. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  43956. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  43957. }
  43958. if (this._microSurfaceTexture) {
  43959. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  43960. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  43961. }
  43962. }
  43963. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43964. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  43965. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43966. if (scene._mirroredCameraPosition) {
  43967. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43968. }
  43969. else {
  43970. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43971. }
  43972. }
  43973. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43974. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  43975. var depth = 1.0;
  43976. if (!refractionTexture.isCube) {
  43977. if (refractionTexture.depth) {
  43978. depth = refractionTexture.depth;
  43979. }
  43980. }
  43981. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  43982. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  43983. }
  43984. }
  43985. // Point size
  43986. if (this.pointsCloud) {
  43987. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43988. }
  43989. // Colors
  43990. if (defines.METALLICWORKFLOW) {
  43991. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  43992. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  43993. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  43994. }
  43995. else {
  43996. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  43997. }
  43998. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  43999. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44000. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44001. // Misc
  44002. this._lightingInfos.x = this._directIntensity;
  44003. this._lightingInfos.y = this._emissiveIntensity;
  44004. this._lightingInfos.z = this._environmentIntensity;
  44005. this._lightingInfos.w = this._specularIntensity;
  44006. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44007. }
  44008. // Textures
  44009. if (scene.texturesEnabled) {
  44010. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44011. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44012. }
  44013. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44014. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44015. }
  44016. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44017. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44018. }
  44019. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44020. if (defines.LODBASEDMICROSFURACE) {
  44021. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44022. }
  44023. else {
  44024. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44025. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44026. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44027. }
  44028. }
  44029. if (defines.ENVIRONMENTBRDF) {
  44030. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44031. }
  44032. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44033. if (defines.LODBASEDMICROSFURACE) {
  44034. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44035. }
  44036. else {
  44037. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44038. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44039. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44040. }
  44041. }
  44042. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44043. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44044. }
  44045. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44046. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44047. }
  44048. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44049. if (this._metallicTexture) {
  44050. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44051. }
  44052. else if (this._reflectivityTexture) {
  44053. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44054. }
  44055. if (this._microSurfaceTexture) {
  44056. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44057. }
  44058. }
  44059. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44060. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44061. }
  44062. }
  44063. // Clip plane
  44064. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44065. // Colors
  44066. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44067. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44068. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44069. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44070. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44071. }
  44072. if (mustRebind || !this.isFrozen) {
  44073. // Lights
  44074. if (scene.lightsEnabled && !this._disableLighting) {
  44075. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44076. }
  44077. // View
  44078. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44079. this.bindView(effect);
  44080. }
  44081. // Fog
  44082. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44083. // Morph targets
  44084. if (defines.NUM_MORPH_INFLUENCERS) {
  44085. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44086. }
  44087. // image processing
  44088. this._imageProcessingConfiguration.bind(this._activeEffect);
  44089. // Log. depth
  44090. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44091. }
  44092. this._uniformBuffer.update();
  44093. this._afterBind(mesh, this._activeEffect);
  44094. };
  44095. /**
  44096. * Returns the animatable textures.
  44097. * @returns - Array of animatable textures.
  44098. */
  44099. PBRBaseMaterial.prototype.getAnimatables = function () {
  44100. var results = [];
  44101. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44102. results.push(this._albedoTexture);
  44103. }
  44104. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44105. results.push(this._ambientTexture);
  44106. }
  44107. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44108. results.push(this._opacityTexture);
  44109. }
  44110. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44111. results.push(this._reflectionTexture);
  44112. }
  44113. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44114. results.push(this._emissiveTexture);
  44115. }
  44116. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44117. results.push(this._metallicTexture);
  44118. }
  44119. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44120. results.push(this._reflectivityTexture);
  44121. }
  44122. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44123. results.push(this._bumpTexture);
  44124. }
  44125. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44126. results.push(this._lightmapTexture);
  44127. }
  44128. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44129. results.push(this._refractionTexture);
  44130. }
  44131. return results;
  44132. };
  44133. /**
  44134. * Returns the texture used for reflections.
  44135. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44136. */
  44137. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44138. if (this._reflectionTexture) {
  44139. return this._reflectionTexture;
  44140. }
  44141. return this.getScene().environmentTexture;
  44142. };
  44143. /**
  44144. * Returns the texture used for refraction or null if none is used.
  44145. * @returns - Refection texture if present. If no refraction texture and refraction
  44146. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44147. */
  44148. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44149. if (this._refractionTexture) {
  44150. return this._refractionTexture;
  44151. }
  44152. if (this._linkRefractionWithTransparency) {
  44153. return this.getScene().environmentTexture;
  44154. }
  44155. return null;
  44156. };
  44157. /**
  44158. * Disposes the resources of the material.
  44159. * @param forceDisposeEffect - Forces the disposal of effects.
  44160. * @param forceDisposeTextures - Forces the disposal of all textures.
  44161. */
  44162. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44163. if (forceDisposeTextures) {
  44164. if (this._albedoTexture) {
  44165. this._albedoTexture.dispose();
  44166. }
  44167. if (this._ambientTexture) {
  44168. this._ambientTexture.dispose();
  44169. }
  44170. if (this._opacityTexture) {
  44171. this._opacityTexture.dispose();
  44172. }
  44173. if (this._reflectionTexture) {
  44174. this._reflectionTexture.dispose();
  44175. }
  44176. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44177. this._environmentBRDFTexture.dispose();
  44178. }
  44179. if (this._emissiveTexture) {
  44180. this._emissiveTexture.dispose();
  44181. }
  44182. if (this._metallicTexture) {
  44183. this._metallicTexture.dispose();
  44184. }
  44185. if (this._reflectivityTexture) {
  44186. this._reflectivityTexture.dispose();
  44187. }
  44188. if (this._bumpTexture) {
  44189. this._bumpTexture.dispose();
  44190. }
  44191. if (this._lightmapTexture) {
  44192. this._lightmapTexture.dispose();
  44193. }
  44194. if (this._refractionTexture) {
  44195. this._refractionTexture.dispose();
  44196. }
  44197. }
  44198. this._renderTargets.dispose();
  44199. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44200. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44201. }
  44202. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44203. };
  44204. /**
  44205. * Stores the reflectivity values based on metallic roughness workflow.
  44206. */
  44207. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44208. __decorate([
  44209. BABYLON.serializeAsImageProcessingConfiguration()
  44210. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44211. __decorate([
  44212. BABYLON.serialize()
  44213. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44214. __decorate([
  44215. BABYLON.serialize()
  44216. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44217. return PBRBaseMaterial;
  44218. }(BABYLON.PushMaterial));
  44219. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44220. })(BABYLON || (BABYLON = {}));
  44221. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44222. var BABYLON;
  44223. (function (BABYLON) {
  44224. /**
  44225. * The Physically based simple base material of BJS.
  44226. *
  44227. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44228. * It is used as the base class for both the specGloss and metalRough conventions.
  44229. */
  44230. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44231. __extends(PBRBaseSimpleMaterial, _super);
  44232. /**
  44233. * Instantiates a new PBRMaterial instance.
  44234. *
  44235. * @param name The material name
  44236. * @param scene The scene the material will be use in.
  44237. */
  44238. function PBRBaseSimpleMaterial(name, scene) {
  44239. var _this = _super.call(this, name, scene) || this;
  44240. /**
  44241. * Number of Simultaneous lights allowed on the material.
  44242. */
  44243. _this.maxSimultaneousLights = 4;
  44244. /**
  44245. * If sets to true, disables all the lights affecting the material.
  44246. */
  44247. _this.disableLighting = false;
  44248. /**
  44249. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44250. */
  44251. _this.invertNormalMapX = false;
  44252. /**
  44253. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44254. */
  44255. _this.invertNormalMapY = false;
  44256. /**
  44257. * Emissivie color used to self-illuminate the model.
  44258. */
  44259. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44260. /**
  44261. * Occlusion Channel Strenght.
  44262. */
  44263. _this.occlusionStrength = 1.0;
  44264. _this.useLightmapAsShadowmap = false;
  44265. _this._useAlphaFromAlbedoTexture = true;
  44266. _this._useAmbientInGrayScale = true;
  44267. return _this;
  44268. }
  44269. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44270. /**
  44271. * Gets the current double sided mode.
  44272. */
  44273. get: function () {
  44274. return this._twoSidedLighting;
  44275. },
  44276. /**
  44277. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44278. */
  44279. set: function (value) {
  44280. if (this._twoSidedLighting === value) {
  44281. return;
  44282. }
  44283. this._twoSidedLighting = value;
  44284. this.backFaceCulling = !value;
  44285. this._markAllSubMeshesAsTexturesDirty();
  44286. },
  44287. enumerable: true,
  44288. configurable: true
  44289. });
  44290. /**
  44291. * Return the active textures of the material.
  44292. */
  44293. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44294. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44295. if (this.environmentTexture) {
  44296. activeTextures.push(this.environmentTexture);
  44297. }
  44298. if (this.normalTexture) {
  44299. activeTextures.push(this.normalTexture);
  44300. }
  44301. if (this.emissiveTexture) {
  44302. activeTextures.push(this.emissiveTexture);
  44303. }
  44304. if (this.occlusionTexture) {
  44305. activeTextures.push(this.occlusionTexture);
  44306. }
  44307. if (this.lightmapTexture) {
  44308. activeTextures.push(this.lightmapTexture);
  44309. }
  44310. return activeTextures;
  44311. };
  44312. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44313. if (_super.prototype.hasTexture.call(this, texture)) {
  44314. return true;
  44315. }
  44316. if (this.lightmapTexture === texture) {
  44317. return true;
  44318. }
  44319. return false;
  44320. };
  44321. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44322. return "PBRBaseSimpleMaterial";
  44323. };
  44324. __decorate([
  44325. BABYLON.serialize(),
  44326. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44327. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44328. __decorate([
  44329. BABYLON.serialize(),
  44330. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44331. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44332. __decorate([
  44333. BABYLON.serializeAsTexture(),
  44334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44335. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44336. __decorate([
  44337. BABYLON.serialize(),
  44338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44339. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44340. __decorate([
  44341. BABYLON.serialize(),
  44342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44343. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44344. __decorate([
  44345. BABYLON.serializeAsTexture(),
  44346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44347. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44348. __decorate([
  44349. BABYLON.serializeAsColor3("emissive"),
  44350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44351. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44352. __decorate([
  44353. BABYLON.serializeAsTexture(),
  44354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44355. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44356. __decorate([
  44357. BABYLON.serialize(),
  44358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44359. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44360. __decorate([
  44361. BABYLON.serializeAsTexture(),
  44362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44363. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44364. __decorate([
  44365. BABYLON.serialize(),
  44366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44367. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44368. __decorate([
  44369. BABYLON.serialize()
  44370. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44371. __decorate([
  44372. BABYLON.serializeAsTexture(),
  44373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44374. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44375. __decorate([
  44376. BABYLON.serialize(),
  44377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44378. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44379. return PBRBaseSimpleMaterial;
  44380. }(BABYLON.PBRBaseMaterial));
  44381. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44382. })(BABYLON || (BABYLON = {}));
  44383. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44384. var BABYLON;
  44385. (function (BABYLON) {
  44386. /**
  44387. * The Physically based material of BJS.
  44388. *
  44389. * This offers the main features of a standard PBR material.
  44390. * For more information, please refer to the documentation :
  44391. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44392. */
  44393. var PBRMaterial = /** @class */ (function (_super) {
  44394. __extends(PBRMaterial, _super);
  44395. /**
  44396. * Instantiates a new PBRMaterial instance.
  44397. *
  44398. * @param name The material name
  44399. * @param scene The scene the material will be use in.
  44400. */
  44401. function PBRMaterial(name, scene) {
  44402. var _this = _super.call(this, name, scene) || this;
  44403. /**
  44404. * Intensity of the direct lights e.g. the four lights available in your scene.
  44405. * This impacts both the direct diffuse and specular highlights.
  44406. */
  44407. _this.directIntensity = 1.0;
  44408. /**
  44409. * Intensity of the emissive part of the material.
  44410. * This helps controlling the emissive effect without modifying the emissive color.
  44411. */
  44412. _this.emissiveIntensity = 1.0;
  44413. /**
  44414. * Intensity of the environment e.g. how much the environment will light the object
  44415. * either through harmonics for rough material or through the refelction for shiny ones.
  44416. */
  44417. _this.environmentIntensity = 1.0;
  44418. /**
  44419. * This is a special control allowing the reduction of the specular highlights coming from the
  44420. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44421. */
  44422. _this.specularIntensity = 1.0;
  44423. /**
  44424. * Debug Control allowing disabling the bump map on this material.
  44425. */
  44426. _this.disableBumpMap = false;
  44427. /**
  44428. * AKA Occlusion Texture Intensity in other nomenclature.
  44429. */
  44430. _this.ambientTextureStrength = 1.0;
  44431. /**
  44432. * The color of a material in ambient lighting.
  44433. */
  44434. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44435. /**
  44436. * AKA Diffuse Color in other nomenclature.
  44437. */
  44438. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44439. /**
  44440. * AKA Specular Color in other nomenclature.
  44441. */
  44442. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44443. /**
  44444. * The color reflected from the material.
  44445. */
  44446. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44447. /**
  44448. * The color emitted from the material.
  44449. */
  44450. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44451. /**
  44452. * AKA Glossiness in other nomenclature.
  44453. */
  44454. _this.microSurface = 1.0;
  44455. /**
  44456. * source material index of refraction (IOR)' / 'destination material IOR.
  44457. */
  44458. _this.indexOfRefraction = 0.66;
  44459. /**
  44460. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44461. */
  44462. _this.invertRefractionY = false;
  44463. /**
  44464. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44465. * Materials half opaque for instance using refraction could benefit from this control.
  44466. */
  44467. _this.linkRefractionWithTransparency = false;
  44468. _this.useLightmapAsShadowmap = false;
  44469. /**
  44470. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44471. */
  44472. _this.useAlphaFromAlbedoTexture = false;
  44473. /**
  44474. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44475. */
  44476. _this.forceAlphaTest = false;
  44477. /**
  44478. * Defines the alpha limits in alpha test mode.
  44479. */
  44480. _this.alphaCutOff = 0.4;
  44481. /**
  44482. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44483. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44484. */
  44485. _this.useSpecularOverAlpha = true;
  44486. /**
  44487. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44488. */
  44489. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44490. /**
  44491. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44492. */
  44493. _this.useRoughnessFromMetallicTextureAlpha = true;
  44494. /**
  44495. * Specifies if the metallic texture contains the roughness information in its green channel.
  44496. */
  44497. _this.useRoughnessFromMetallicTextureGreen = false;
  44498. /**
  44499. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44500. */
  44501. _this.useMetallnessFromMetallicTextureBlue = false;
  44502. /**
  44503. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44504. */
  44505. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44506. /**
  44507. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44508. */
  44509. _this.useAmbientInGrayScale = false;
  44510. /**
  44511. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44512. * The material will try to infer what glossiness each pixel should be.
  44513. */
  44514. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44515. /**
  44516. * BJS is using an harcoded light falloff based on a manually sets up range.
  44517. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44518. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44519. */
  44520. _this.usePhysicalLightFalloff = true;
  44521. /**
  44522. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44523. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44524. */
  44525. _this.useRadianceOverAlpha = true;
  44526. /**
  44527. * Allows using an object space normal map (instead of tangent space).
  44528. */
  44529. _this.useObjectSpaceNormalMap = false;
  44530. /**
  44531. * Allows using the bump map in parallax mode.
  44532. */
  44533. _this.useParallax = false;
  44534. /**
  44535. * Allows using the bump map in parallax occlusion mode.
  44536. */
  44537. _this.useParallaxOcclusion = false;
  44538. /**
  44539. * Controls the scale bias of the parallax mode.
  44540. */
  44541. _this.parallaxScaleBias = 0.05;
  44542. /**
  44543. * If sets to true, disables all the lights affecting the material.
  44544. */
  44545. _this.disableLighting = false;
  44546. /**
  44547. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44548. */
  44549. _this.forceIrradianceInFragment = false;
  44550. /**
  44551. * Number of Simultaneous lights allowed on the material.
  44552. */
  44553. _this.maxSimultaneousLights = 4;
  44554. /**
  44555. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44556. */
  44557. _this.invertNormalMapX = false;
  44558. /**
  44559. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44560. */
  44561. _this.invertNormalMapY = false;
  44562. /**
  44563. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44564. */
  44565. _this.twoSidedLighting = false;
  44566. /**
  44567. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44568. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44569. */
  44570. _this.useAlphaFresnel = false;
  44571. /**
  44572. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44573. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44574. */
  44575. _this.useLinearAlphaFresnel = false;
  44576. /**
  44577. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44578. * And/Or occlude the blended part.
  44579. */
  44580. _this.environmentBRDFTexture = null;
  44581. /**
  44582. * Force normal to face away from face.
  44583. */
  44584. _this.forceNormalForward = false;
  44585. /**
  44586. * Enables specular anti aliasing in the PBR shader.
  44587. * It will both interacts on the Geometry for analytical and IBL lighting.
  44588. * It also prefilter the roughness map based on the bump values.
  44589. */
  44590. _this.enableSpecularAntiAliasing = false;
  44591. /**
  44592. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44593. * makes the reflect vector face the model (under horizon).
  44594. */
  44595. _this.useHorizonOcclusion = true;
  44596. /**
  44597. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44598. * too much the area relying on ambient texture to define their ambient occlusion.
  44599. */
  44600. _this.useRadianceOcclusion = true;
  44601. /**
  44602. * If set to true, no lighting calculations will be applied.
  44603. */
  44604. _this.unlit = false;
  44605. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44606. return _this;
  44607. }
  44608. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44609. /**
  44610. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44611. */
  44612. get: function () {
  44613. return this._PBRMATERIAL_OPAQUE;
  44614. },
  44615. enumerable: true,
  44616. configurable: true
  44617. });
  44618. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44619. /**
  44620. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44621. */
  44622. get: function () {
  44623. return this._PBRMATERIAL_ALPHATEST;
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44629. /**
  44630. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44631. */
  44632. get: function () {
  44633. return this._PBRMATERIAL_ALPHABLEND;
  44634. },
  44635. enumerable: true,
  44636. configurable: true
  44637. });
  44638. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44639. /**
  44640. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44641. * They are also discarded below the alpha cutoff threshold to improve performances.
  44642. */
  44643. get: function () {
  44644. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44645. },
  44646. enumerable: true,
  44647. configurable: true
  44648. });
  44649. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44650. /**
  44651. * Gets the image processing configuration used either in this material.
  44652. */
  44653. get: function () {
  44654. return this._imageProcessingConfiguration;
  44655. },
  44656. /**
  44657. * Sets the Default image processing configuration used either in the this material.
  44658. *
  44659. * If sets to null, the scene one is in use.
  44660. */
  44661. set: function (value) {
  44662. this._attachImageProcessingConfiguration(value);
  44663. // Ensure the effect will be rebuilt.
  44664. this._markAllSubMeshesAsTexturesDirty();
  44665. },
  44666. enumerable: true,
  44667. configurable: true
  44668. });
  44669. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44670. /**
  44671. * Gets wether the color curves effect is enabled.
  44672. */
  44673. get: function () {
  44674. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44675. },
  44676. /**
  44677. * Sets wether the color curves effect is enabled.
  44678. */
  44679. set: function (value) {
  44680. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44681. },
  44682. enumerable: true,
  44683. configurable: true
  44684. });
  44685. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44686. /**
  44687. * Gets wether the color grading effect is enabled.
  44688. */
  44689. get: function () {
  44690. return this.imageProcessingConfiguration.colorGradingEnabled;
  44691. },
  44692. /**
  44693. * Gets wether the color grading effect is enabled.
  44694. */
  44695. set: function (value) {
  44696. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44697. },
  44698. enumerable: true,
  44699. configurable: true
  44700. });
  44701. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44702. /**
  44703. * Gets wether tonemapping is enabled or not.
  44704. */
  44705. get: function () {
  44706. return this._imageProcessingConfiguration.toneMappingEnabled;
  44707. },
  44708. /**
  44709. * Sets wether tonemapping is enabled or not
  44710. */
  44711. set: function (value) {
  44712. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44713. },
  44714. enumerable: true,
  44715. configurable: true
  44716. });
  44717. ;
  44718. ;
  44719. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44720. /**
  44721. * The camera exposure used on this material.
  44722. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44723. * This corresponds to a photographic exposure.
  44724. */
  44725. get: function () {
  44726. return this._imageProcessingConfiguration.exposure;
  44727. },
  44728. /**
  44729. * The camera exposure used on this material.
  44730. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44731. * This corresponds to a photographic exposure.
  44732. */
  44733. set: function (value) {
  44734. this._imageProcessingConfiguration.exposure = value;
  44735. },
  44736. enumerable: true,
  44737. configurable: true
  44738. });
  44739. ;
  44740. ;
  44741. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44742. /**
  44743. * Gets The camera contrast used on this material.
  44744. */
  44745. get: function () {
  44746. return this._imageProcessingConfiguration.contrast;
  44747. },
  44748. /**
  44749. * Sets The camera contrast used on this material.
  44750. */
  44751. set: function (value) {
  44752. this._imageProcessingConfiguration.contrast = value;
  44753. },
  44754. enumerable: true,
  44755. configurable: true
  44756. });
  44757. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44758. /**
  44759. * Gets the Color Grading 2D Lookup Texture.
  44760. */
  44761. get: function () {
  44762. return this._imageProcessingConfiguration.colorGradingTexture;
  44763. },
  44764. /**
  44765. * Sets the Color Grading 2D Lookup Texture.
  44766. */
  44767. set: function (value) {
  44768. this._imageProcessingConfiguration.colorGradingTexture = value;
  44769. },
  44770. enumerable: true,
  44771. configurable: true
  44772. });
  44773. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44774. /**
  44775. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44776. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44777. * 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;
  44778. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44779. */
  44780. get: function () {
  44781. return this._imageProcessingConfiguration.colorCurves;
  44782. },
  44783. /**
  44784. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44785. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44786. * 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;
  44787. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44788. */
  44789. set: function (value) {
  44790. this._imageProcessingConfiguration.colorCurves = value;
  44791. },
  44792. enumerable: true,
  44793. configurable: true
  44794. });
  44795. /**
  44796. * Returns the name of this material class.
  44797. */
  44798. PBRMaterial.prototype.getClassName = function () {
  44799. return "PBRMaterial";
  44800. };
  44801. /**
  44802. * Returns an array of the actively used textures.
  44803. * @returns - Array of BaseTextures
  44804. */
  44805. PBRMaterial.prototype.getActiveTextures = function () {
  44806. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44807. if (this._albedoTexture) {
  44808. activeTextures.push(this._albedoTexture);
  44809. }
  44810. if (this._ambientTexture) {
  44811. activeTextures.push(this._ambientTexture);
  44812. }
  44813. if (this._opacityTexture) {
  44814. activeTextures.push(this._opacityTexture);
  44815. }
  44816. if (this._reflectionTexture) {
  44817. activeTextures.push(this._reflectionTexture);
  44818. }
  44819. if (this._emissiveTexture) {
  44820. activeTextures.push(this._emissiveTexture);
  44821. }
  44822. if (this._reflectivityTexture) {
  44823. activeTextures.push(this._reflectivityTexture);
  44824. }
  44825. if (this._metallicTexture) {
  44826. activeTextures.push(this._metallicTexture);
  44827. }
  44828. if (this._microSurfaceTexture) {
  44829. activeTextures.push(this._microSurfaceTexture);
  44830. }
  44831. if (this._bumpTexture) {
  44832. activeTextures.push(this._bumpTexture);
  44833. }
  44834. if (this._lightmapTexture) {
  44835. activeTextures.push(this._lightmapTexture);
  44836. }
  44837. if (this._refractionTexture) {
  44838. activeTextures.push(this._refractionTexture);
  44839. }
  44840. return activeTextures;
  44841. };
  44842. /**
  44843. * Checks to see if a texture is used in the material.
  44844. * @param texture - Base texture to use.
  44845. * @returns - Boolean specifying if a texture is used in the material.
  44846. */
  44847. PBRMaterial.prototype.hasTexture = function (texture) {
  44848. if (_super.prototype.hasTexture.call(this, texture)) {
  44849. return true;
  44850. }
  44851. if (this._albedoTexture === texture) {
  44852. return true;
  44853. }
  44854. if (this._ambientTexture === texture) {
  44855. return true;
  44856. }
  44857. if (this._opacityTexture === texture) {
  44858. return true;
  44859. }
  44860. if (this._reflectionTexture === texture) {
  44861. return true;
  44862. }
  44863. if (this._reflectivityTexture === texture) {
  44864. return true;
  44865. }
  44866. if (this._metallicTexture === texture) {
  44867. return true;
  44868. }
  44869. if (this._microSurfaceTexture === texture) {
  44870. return true;
  44871. }
  44872. if (this._bumpTexture === texture) {
  44873. return true;
  44874. }
  44875. if (this._lightmapTexture === texture) {
  44876. return true;
  44877. }
  44878. if (this._refractionTexture === texture) {
  44879. return true;
  44880. }
  44881. return false;
  44882. };
  44883. /**
  44884. * Makes a duplicate of the current material.
  44885. * @param name - name to use for the new material.
  44886. */
  44887. PBRMaterial.prototype.clone = function (name) {
  44888. var _this = this;
  44889. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  44890. clone.id = name;
  44891. clone.name = name;
  44892. return clone;
  44893. };
  44894. /**
  44895. * Serializes this PBR Material.
  44896. * @returns - An object with the serialized material.
  44897. */
  44898. PBRMaterial.prototype.serialize = function () {
  44899. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44900. serializationObject.customType = "BABYLON.PBRMaterial";
  44901. return serializationObject;
  44902. };
  44903. // Statics
  44904. /**
  44905. * Parses a PBR Material from a serialized object.
  44906. * @param source - Serialized object.
  44907. * @param scene - BJS scene instance.
  44908. * @param rootUrl - url for the scene object
  44909. * @returns - PBRMaterial
  44910. */
  44911. PBRMaterial.Parse = function (source, scene, rootUrl) {
  44912. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  44913. };
  44914. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  44915. /**
  44916. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44917. */
  44918. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  44919. /**
  44920. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44921. */
  44922. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  44923. /**
  44924. * 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.
  44925. * They are also discarded below the alpha cutoff threshold to improve performances.
  44926. */
  44927. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  44928. __decorate([
  44929. BABYLON.serialize(),
  44930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44931. ], PBRMaterial.prototype, "directIntensity", void 0);
  44932. __decorate([
  44933. BABYLON.serialize(),
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44935. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  44936. __decorate([
  44937. BABYLON.serialize(),
  44938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44939. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  44940. __decorate([
  44941. BABYLON.serialize(),
  44942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44943. ], PBRMaterial.prototype, "specularIntensity", void 0);
  44944. __decorate([
  44945. BABYLON.serialize(),
  44946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44947. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  44948. __decorate([
  44949. BABYLON.serializeAsTexture(),
  44950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44951. ], PBRMaterial.prototype, "albedoTexture", void 0);
  44952. __decorate([
  44953. BABYLON.serializeAsTexture(),
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44955. ], PBRMaterial.prototype, "ambientTexture", void 0);
  44956. __decorate([
  44957. BABYLON.serialize(),
  44958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44959. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  44960. __decorate([
  44961. BABYLON.serializeAsTexture(),
  44962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44963. ], PBRMaterial.prototype, "opacityTexture", void 0);
  44964. __decorate([
  44965. BABYLON.serializeAsTexture(),
  44966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44967. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  44968. __decorate([
  44969. BABYLON.serializeAsTexture(),
  44970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44971. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  44972. __decorate([
  44973. BABYLON.serializeAsTexture(),
  44974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44975. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  44976. __decorate([
  44977. BABYLON.serializeAsTexture(),
  44978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44979. ], PBRMaterial.prototype, "metallicTexture", void 0);
  44980. __decorate([
  44981. BABYLON.serialize(),
  44982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44983. ], PBRMaterial.prototype, "metallic", void 0);
  44984. __decorate([
  44985. BABYLON.serialize(),
  44986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44987. ], PBRMaterial.prototype, "roughness", void 0);
  44988. __decorate([
  44989. BABYLON.serializeAsTexture(),
  44990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44991. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  44992. __decorate([
  44993. BABYLON.serializeAsTexture(),
  44994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44995. ], PBRMaterial.prototype, "bumpTexture", void 0);
  44996. __decorate([
  44997. BABYLON.serializeAsTexture(),
  44998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44999. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45000. __decorate([
  45001. BABYLON.serializeAsTexture(),
  45002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45003. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45004. __decorate([
  45005. BABYLON.serializeAsColor3("ambient"),
  45006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45007. ], PBRMaterial.prototype, "ambientColor", void 0);
  45008. __decorate([
  45009. BABYLON.serializeAsColor3("albedo"),
  45010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45011. ], PBRMaterial.prototype, "albedoColor", void 0);
  45012. __decorate([
  45013. BABYLON.serializeAsColor3("reflectivity"),
  45014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45015. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45016. __decorate([
  45017. BABYLON.serializeAsColor3("reflection"),
  45018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45019. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45020. __decorate([
  45021. BABYLON.serializeAsColor3("emissive"),
  45022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45023. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45024. __decorate([
  45025. BABYLON.serialize(),
  45026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45027. ], PBRMaterial.prototype, "microSurface", void 0);
  45028. __decorate([
  45029. BABYLON.serialize(),
  45030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45031. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45032. __decorate([
  45033. BABYLON.serialize(),
  45034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45035. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45036. __decorate([
  45037. BABYLON.serialize(),
  45038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45039. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45040. __decorate([
  45041. BABYLON.serialize(),
  45042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45043. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45044. __decorate([
  45045. BABYLON.serialize(),
  45046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45047. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45048. __decorate([
  45049. BABYLON.serialize(),
  45050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45051. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45052. __decorate([
  45053. BABYLON.serialize(),
  45054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45055. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45056. __decorate([
  45057. BABYLON.serialize(),
  45058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45059. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45060. __decorate([
  45061. BABYLON.serialize(),
  45062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45063. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45064. __decorate([
  45065. BABYLON.serialize(),
  45066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45067. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45068. __decorate([
  45069. BABYLON.serialize(),
  45070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45071. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45072. __decorate([
  45073. BABYLON.serialize(),
  45074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45075. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45076. __decorate([
  45077. BABYLON.serialize(),
  45078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45079. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45080. __decorate([
  45081. BABYLON.serialize(),
  45082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45083. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45084. __decorate([
  45085. BABYLON.serialize(),
  45086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45087. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45088. __decorate([
  45089. BABYLON.serialize(),
  45090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45091. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45092. __decorate([
  45093. BABYLON.serialize(),
  45094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45095. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45096. __decorate([
  45097. BABYLON.serialize(),
  45098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45099. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45100. __decorate([
  45101. BABYLON.serialize(),
  45102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45103. ], PBRMaterial.prototype, "useParallax", void 0);
  45104. __decorate([
  45105. BABYLON.serialize(),
  45106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45107. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45108. __decorate([
  45109. BABYLON.serialize(),
  45110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45111. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45112. __decorate([
  45113. BABYLON.serialize(),
  45114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45115. ], PBRMaterial.prototype, "disableLighting", void 0);
  45116. __decorate([
  45117. BABYLON.serialize(),
  45118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45119. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45120. __decorate([
  45121. BABYLON.serialize(),
  45122. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45123. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45124. __decorate([
  45125. BABYLON.serialize(),
  45126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45127. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45128. __decorate([
  45129. BABYLON.serialize(),
  45130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45131. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45132. __decorate([
  45133. BABYLON.serialize(),
  45134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45135. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45136. __decorate([
  45137. BABYLON.serialize(),
  45138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45139. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45140. __decorate([
  45141. BABYLON.serialize(),
  45142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45143. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45144. __decorate([
  45145. BABYLON.serializeAsTexture(),
  45146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45147. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45148. __decorate([
  45149. BABYLON.serialize(),
  45150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45151. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45152. __decorate([
  45153. BABYLON.serialize(),
  45154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45155. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45156. __decorate([
  45157. BABYLON.serialize(),
  45158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45159. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45160. __decorate([
  45161. BABYLON.serialize(),
  45162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45163. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45164. __decorate([
  45165. BABYLON.serialize(),
  45166. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45167. ], PBRMaterial.prototype, "unlit", void 0);
  45168. return PBRMaterial;
  45169. }(BABYLON.PBRBaseMaterial));
  45170. BABYLON.PBRMaterial = PBRMaterial;
  45171. })(BABYLON || (BABYLON = {}));
  45172. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45173. var BABYLON;
  45174. (function (BABYLON) {
  45175. /**
  45176. * The PBR material of BJS following the metal roughness convention.
  45177. *
  45178. * This fits to the PBR convention in the GLTF definition:
  45179. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45180. */
  45181. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45182. __extends(PBRMetallicRoughnessMaterial, _super);
  45183. /**
  45184. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45185. *
  45186. * @param name The material name
  45187. * @param scene The scene the material will be use in.
  45188. */
  45189. function PBRMetallicRoughnessMaterial(name, scene) {
  45190. var _this = _super.call(this, name, scene) || this;
  45191. _this._useRoughnessFromMetallicTextureAlpha = false;
  45192. _this._useRoughnessFromMetallicTextureGreen = true;
  45193. _this._useMetallnessFromMetallicTextureBlue = true;
  45194. _this.metallic = 1.0;
  45195. _this.roughness = 1.0;
  45196. return _this;
  45197. }
  45198. /**
  45199. * Return the currrent class name of the material.
  45200. */
  45201. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45202. return "PBRMetallicRoughnessMaterial";
  45203. };
  45204. /**
  45205. * Return the active textures of the material.
  45206. */
  45207. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45208. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45209. if (this.baseTexture) {
  45210. activeTextures.push(this.baseTexture);
  45211. }
  45212. if (this.metallicRoughnessTexture) {
  45213. activeTextures.push(this.metallicRoughnessTexture);
  45214. }
  45215. return activeTextures;
  45216. };
  45217. /**
  45218. * Checks to see if a texture is used in the material.
  45219. * @param texture - Base texture to use.
  45220. * @returns - Boolean specifying if a texture is used in the material.
  45221. */
  45222. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45223. if (_super.prototype.hasTexture.call(this, texture)) {
  45224. return true;
  45225. }
  45226. if (this.baseTexture === texture) {
  45227. return true;
  45228. }
  45229. if (this.metallicRoughnessTexture === texture) {
  45230. return true;
  45231. }
  45232. return false;
  45233. };
  45234. /**
  45235. * Makes a duplicate of the current material.
  45236. * @param name - name to use for the new material.
  45237. */
  45238. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45239. var _this = this;
  45240. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45241. clone.id = name;
  45242. clone.name = name;
  45243. return clone;
  45244. };
  45245. /**
  45246. * Serialize the material to a parsable JSON object.
  45247. */
  45248. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45250. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45251. return serializationObject;
  45252. };
  45253. /**
  45254. * Parses a JSON object correponding to the serialize function.
  45255. */
  45256. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45257. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45258. };
  45259. __decorate([
  45260. BABYLON.serializeAsColor3(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45262. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45263. __decorate([
  45264. BABYLON.serializeAsTexture(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45266. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45267. __decorate([
  45268. BABYLON.serialize(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45270. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45271. __decorate([
  45272. BABYLON.serialize(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45275. __decorate([
  45276. BABYLON.serializeAsTexture(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45278. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45279. return PBRMetallicRoughnessMaterial;
  45280. }(BABYLON.PBRBaseSimpleMaterial));
  45281. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45282. })(BABYLON || (BABYLON = {}));
  45283. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45284. var BABYLON;
  45285. (function (BABYLON) {
  45286. /**
  45287. * The PBR material of BJS following the specular glossiness convention.
  45288. *
  45289. * This fits to the PBR convention in the GLTF definition:
  45290. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45291. */
  45292. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45293. __extends(PBRSpecularGlossinessMaterial, _super);
  45294. /**
  45295. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45296. *
  45297. * @param name The material name
  45298. * @param scene The scene the material will be use in.
  45299. */
  45300. function PBRSpecularGlossinessMaterial(name, scene) {
  45301. var _this = _super.call(this, name, scene) || this;
  45302. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45303. return _this;
  45304. }
  45305. /**
  45306. * Return the currrent class name of the material.
  45307. */
  45308. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45309. return "PBRSpecularGlossinessMaterial";
  45310. };
  45311. /**
  45312. * Return the active textures of the material.
  45313. */
  45314. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45315. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45316. if (this.diffuseTexture) {
  45317. activeTextures.push(this.diffuseTexture);
  45318. }
  45319. if (this.specularGlossinessTexture) {
  45320. activeTextures.push(this.specularGlossinessTexture);
  45321. }
  45322. return activeTextures;
  45323. };
  45324. /**
  45325. * Checks to see if a texture is used in the material.
  45326. * @param texture - Base texture to use.
  45327. * @returns - Boolean specifying if a texture is used in the material.
  45328. */
  45329. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45330. if (_super.prototype.hasTexture.call(this, texture)) {
  45331. return true;
  45332. }
  45333. if (this.diffuseTexture === texture) {
  45334. return true;
  45335. }
  45336. if (this.specularGlossinessTexture === texture) {
  45337. return true;
  45338. }
  45339. return false;
  45340. };
  45341. /**
  45342. * Makes a duplicate of the current material.
  45343. * @param name - name to use for the new material.
  45344. */
  45345. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45346. var _this = this;
  45347. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45348. clone.id = name;
  45349. clone.name = name;
  45350. return clone;
  45351. };
  45352. /**
  45353. * Serialize the material to a parsable JSON object.
  45354. */
  45355. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45357. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45358. return serializationObject;
  45359. };
  45360. /**
  45361. * Parses a JSON object correponding to the serialize function.
  45362. */
  45363. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45364. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45365. };
  45366. __decorate([
  45367. BABYLON.serializeAsColor3("diffuse"),
  45368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45369. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45370. __decorate([
  45371. BABYLON.serializeAsTexture(),
  45372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45373. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45374. __decorate([
  45375. BABYLON.serializeAsColor3("specular"),
  45376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45377. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45378. __decorate([
  45379. BABYLON.serialize(),
  45380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45381. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45382. __decorate([
  45383. BABYLON.serializeAsTexture(),
  45384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45385. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45386. return PBRSpecularGlossinessMaterial;
  45387. }(BABYLON.PBRBaseSimpleMaterial));
  45388. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45389. })(BABYLON || (BABYLON = {}));
  45390. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45391. var BABYLON;
  45392. (function (BABYLON) {
  45393. BABYLON.CameraInputTypes = {};
  45394. var CameraInputsManager = /** @class */ (function () {
  45395. function CameraInputsManager(camera) {
  45396. this.attached = {};
  45397. this.camera = camera;
  45398. this.checkInputs = function () { };
  45399. }
  45400. /**
  45401. * Add an input method to a camera
  45402. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45403. * @param input camera input method
  45404. */
  45405. CameraInputsManager.prototype.add = function (input) {
  45406. var type = input.getSimpleName();
  45407. if (this.attached[type]) {
  45408. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45409. return;
  45410. }
  45411. this.attached[type] = input;
  45412. input.camera = this.camera;
  45413. //for checkInputs, we are dynamically creating a function
  45414. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45415. if (input.checkInputs) {
  45416. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45417. }
  45418. if (this.attachedElement) {
  45419. input.attachControl(this.attachedElement);
  45420. }
  45421. };
  45422. /**
  45423. * Remove a specific input method from a camera
  45424. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45425. * @param inputToRemove camera input method
  45426. */
  45427. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45428. for (var cam in this.attached) {
  45429. var input = this.attached[cam];
  45430. if (input === inputToRemove) {
  45431. input.detachControl(this.attachedElement);
  45432. input.camera = null;
  45433. delete this.attached[cam];
  45434. this.rebuildInputCheck();
  45435. }
  45436. }
  45437. };
  45438. CameraInputsManager.prototype.removeByType = function (inputType) {
  45439. for (var cam in this.attached) {
  45440. var input = this.attached[cam];
  45441. if (input.getClassName() === inputType) {
  45442. input.detachControl(this.attachedElement);
  45443. input.camera = null;
  45444. delete this.attached[cam];
  45445. this.rebuildInputCheck();
  45446. }
  45447. }
  45448. };
  45449. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45450. var current = this.checkInputs;
  45451. return function () {
  45452. current();
  45453. fn();
  45454. };
  45455. };
  45456. CameraInputsManager.prototype.attachInput = function (input) {
  45457. if (this.attachedElement) {
  45458. input.attachControl(this.attachedElement, this.noPreventDefault);
  45459. }
  45460. };
  45461. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45462. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45463. if (this.attachedElement) {
  45464. return;
  45465. }
  45466. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45467. this.attachedElement = element;
  45468. this.noPreventDefault = noPreventDefault;
  45469. for (var cam in this.attached) {
  45470. this.attached[cam].attachControl(element, noPreventDefault);
  45471. }
  45472. };
  45473. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45474. if (disconnect === void 0) { disconnect = false; }
  45475. if (this.attachedElement !== element) {
  45476. return;
  45477. }
  45478. for (var cam in this.attached) {
  45479. this.attached[cam].detachControl(element);
  45480. if (disconnect) {
  45481. this.attached[cam].camera = null;
  45482. }
  45483. }
  45484. this.attachedElement = null;
  45485. };
  45486. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45487. this.checkInputs = function () { };
  45488. for (var cam in this.attached) {
  45489. var input = this.attached[cam];
  45490. if (input.checkInputs) {
  45491. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45492. }
  45493. }
  45494. };
  45495. /**
  45496. * Remove all attached input methods from a camera
  45497. */
  45498. CameraInputsManager.prototype.clear = function () {
  45499. if (this.attachedElement) {
  45500. this.detachElement(this.attachedElement, true);
  45501. }
  45502. this.attached = {};
  45503. this.attachedElement = null;
  45504. this.checkInputs = function () { };
  45505. };
  45506. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45507. var inputs = {};
  45508. for (var cam in this.attached) {
  45509. var input = this.attached[cam];
  45510. var res = BABYLON.SerializationHelper.Serialize(input);
  45511. inputs[input.getClassName()] = res;
  45512. }
  45513. serializedCamera.inputsmgr = inputs;
  45514. };
  45515. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45516. var parsedInputs = parsedCamera.inputsmgr;
  45517. if (parsedInputs) {
  45518. this.clear();
  45519. for (var n in parsedInputs) {
  45520. var construct = BABYLON.CameraInputTypes[n];
  45521. if (construct) {
  45522. var parsedinput = parsedInputs[n];
  45523. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45524. this.add(input);
  45525. }
  45526. }
  45527. }
  45528. else {
  45529. //2016-03-08 this part is for managing backward compatibility
  45530. for (var n in this.attached) {
  45531. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45532. if (construct) {
  45533. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45534. this.remove(this.attached[n]);
  45535. this.add(input);
  45536. }
  45537. }
  45538. }
  45539. };
  45540. return CameraInputsManager;
  45541. }());
  45542. BABYLON.CameraInputsManager = CameraInputsManager;
  45543. })(BABYLON || (BABYLON = {}));
  45544. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45545. var BABYLON;
  45546. (function (BABYLON) {
  45547. var TargetCamera = /** @class */ (function (_super) {
  45548. __extends(TargetCamera, _super);
  45549. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45550. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45551. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45552. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45553. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45554. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45555. _this.speed = 2.0;
  45556. _this.noRotationConstraint = false;
  45557. _this.lockedTarget = null;
  45558. _this._currentTarget = BABYLON.Vector3.Zero();
  45559. _this._viewMatrix = BABYLON.Matrix.Zero();
  45560. _this._camMatrix = BABYLON.Matrix.Zero();
  45561. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45562. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45563. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45564. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45565. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45566. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45567. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45568. return _this;
  45569. }
  45570. TargetCamera.prototype.getFrontPosition = function (distance) {
  45571. this.getWorldMatrix();
  45572. var direction = this.getTarget().subtract(this.position);
  45573. direction.normalize();
  45574. direction.scaleInPlace(distance);
  45575. return this.globalPosition.add(direction);
  45576. };
  45577. TargetCamera.prototype._getLockedTargetPosition = function () {
  45578. if (!this.lockedTarget) {
  45579. return null;
  45580. }
  45581. if (this.lockedTarget.absolutePosition) {
  45582. this.lockedTarget.computeWorldMatrix();
  45583. }
  45584. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45585. };
  45586. TargetCamera.prototype.storeState = function () {
  45587. this._storedPosition = this.position.clone();
  45588. this._storedRotation = this.rotation.clone();
  45589. if (this.rotationQuaternion) {
  45590. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45591. }
  45592. return _super.prototype.storeState.call(this);
  45593. };
  45594. /**
  45595. * Restored camera state. You must call storeState() first
  45596. */
  45597. TargetCamera.prototype._restoreStateValues = function () {
  45598. if (!_super.prototype._restoreStateValues.call(this)) {
  45599. return false;
  45600. }
  45601. this.position = this._storedPosition.clone();
  45602. this.rotation = this._storedRotation.clone();
  45603. if (this.rotationQuaternion) {
  45604. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45605. }
  45606. this.cameraDirection.copyFromFloats(0, 0, 0);
  45607. this.cameraRotation.copyFromFloats(0, 0);
  45608. return true;
  45609. };
  45610. // Cache
  45611. TargetCamera.prototype._initCache = function () {
  45612. _super.prototype._initCache.call(this);
  45613. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45614. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45615. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45616. };
  45617. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45618. if (!ignoreParentClass) {
  45619. _super.prototype._updateCache.call(this);
  45620. }
  45621. var lockedTargetPosition = this._getLockedTargetPosition();
  45622. if (!lockedTargetPosition) {
  45623. this._cache.lockedTarget = null;
  45624. }
  45625. else {
  45626. if (!this._cache.lockedTarget) {
  45627. this._cache.lockedTarget = lockedTargetPosition.clone();
  45628. }
  45629. else {
  45630. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45631. }
  45632. }
  45633. this._cache.rotation.copyFrom(this.rotation);
  45634. if (this.rotationQuaternion)
  45635. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45636. };
  45637. // Synchronized
  45638. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45639. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45640. return false;
  45641. }
  45642. var lockedTargetPosition = this._getLockedTargetPosition();
  45643. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45644. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45645. };
  45646. // Methods
  45647. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45648. var engine = this.getEngine();
  45649. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45650. };
  45651. // Target
  45652. TargetCamera.prototype.setTarget = function (target) {
  45653. this.upVector.normalize();
  45654. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45655. this._camMatrix.invert();
  45656. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45657. var vDir = target.subtract(this.position);
  45658. if (vDir.x >= 0.0) {
  45659. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45660. }
  45661. else {
  45662. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45663. }
  45664. this.rotation.z = 0;
  45665. if (isNaN(this.rotation.x)) {
  45666. this.rotation.x = 0;
  45667. }
  45668. if (isNaN(this.rotation.y)) {
  45669. this.rotation.y = 0;
  45670. }
  45671. if (isNaN(this.rotation.z)) {
  45672. this.rotation.z = 0;
  45673. }
  45674. if (this.rotationQuaternion) {
  45675. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45676. }
  45677. };
  45678. /**
  45679. * Return the current target position of the camera. This value is expressed in local space.
  45680. */
  45681. TargetCamera.prototype.getTarget = function () {
  45682. return this._currentTarget;
  45683. };
  45684. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45685. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45686. };
  45687. TargetCamera.prototype._updatePosition = function () {
  45688. if (this.parent) {
  45689. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45690. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45691. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45692. return;
  45693. }
  45694. this.position.addInPlace(this.cameraDirection);
  45695. };
  45696. TargetCamera.prototype._checkInputs = function () {
  45697. var needToMove = this._decideIfNeedsToMove();
  45698. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45699. // Move
  45700. if (needToMove) {
  45701. this._updatePosition();
  45702. }
  45703. // Rotate
  45704. if (needToRotate) {
  45705. this.rotation.x += this.cameraRotation.x;
  45706. this.rotation.y += this.cameraRotation.y;
  45707. //rotate, if quaternion is set and rotation was used
  45708. if (this.rotationQuaternion) {
  45709. var len = this.rotation.lengthSquared();
  45710. if (len) {
  45711. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45712. }
  45713. }
  45714. if (!this.noRotationConstraint) {
  45715. var limit = (Math.PI / 2) * 0.95;
  45716. if (this.rotation.x > limit)
  45717. this.rotation.x = limit;
  45718. if (this.rotation.x < -limit)
  45719. this.rotation.x = -limit;
  45720. }
  45721. }
  45722. // Inertia
  45723. if (needToMove) {
  45724. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45725. this.cameraDirection.x = 0;
  45726. }
  45727. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45728. this.cameraDirection.y = 0;
  45729. }
  45730. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45731. this.cameraDirection.z = 0;
  45732. }
  45733. this.cameraDirection.scaleInPlace(this.inertia);
  45734. }
  45735. if (needToRotate) {
  45736. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45737. this.cameraRotation.x = 0;
  45738. }
  45739. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45740. this.cameraRotation.y = 0;
  45741. }
  45742. this.cameraRotation.scaleInPlace(this.inertia);
  45743. }
  45744. _super.prototype._checkInputs.call(this);
  45745. };
  45746. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45747. if (this.rotationQuaternion) {
  45748. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45749. }
  45750. else {
  45751. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45752. }
  45753. //update the up vector!
  45754. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45755. };
  45756. TargetCamera.prototype._getViewMatrix = function () {
  45757. if (this.lockedTarget) {
  45758. this.setTarget(this._getLockedTargetPosition());
  45759. }
  45760. // Compute
  45761. this._updateCameraRotationMatrix();
  45762. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45763. // Computing target and final matrix
  45764. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45765. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  45766. return this._viewMatrix;
  45767. };
  45768. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  45769. if (this.parent) {
  45770. var parentWorldMatrix = this.parent.getWorldMatrix();
  45771. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  45772. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  45773. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  45774. this._markSyncedWithParent();
  45775. }
  45776. else {
  45777. this._globalPosition.copyFrom(this.position);
  45778. this._globalCurrentTarget.copyFrom(target);
  45779. this._globalCurrentUpVector.copyFrom(up);
  45780. }
  45781. if (this.getScene().useRightHandedSystem) {
  45782. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45783. }
  45784. else {
  45785. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45786. }
  45787. };
  45788. /**
  45789. * @override
  45790. * Override Camera.createRigCamera
  45791. */
  45792. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45793. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45794. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45795. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45796. if (!this.rotationQuaternion) {
  45797. this.rotationQuaternion = new BABYLON.Quaternion();
  45798. }
  45799. rigCamera._cameraRigParams = {};
  45800. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45801. }
  45802. return rigCamera;
  45803. }
  45804. return null;
  45805. };
  45806. /**
  45807. * @override
  45808. * Override Camera._updateRigCameras
  45809. */
  45810. TargetCamera.prototype._updateRigCameras = function () {
  45811. var camLeft = this._rigCameras[0];
  45812. var camRight = this._rigCameras[1];
  45813. switch (this.cameraRigMode) {
  45814. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45815. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45816. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45817. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45818. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45819. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45820. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45821. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45822. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45823. camLeft.setTarget(this.getTarget());
  45824. camRight.setTarget(this.getTarget());
  45825. break;
  45826. case BABYLON.Camera.RIG_MODE_VR:
  45827. if (camLeft.rotationQuaternion) {
  45828. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45829. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45830. }
  45831. else {
  45832. camLeft.rotation.copyFrom(this.rotation);
  45833. camRight.rotation.copyFrom(this.rotation);
  45834. }
  45835. camLeft.position.copyFrom(this.position);
  45836. camRight.position.copyFrom(this.position);
  45837. break;
  45838. }
  45839. _super.prototype._updateRigCameras.call(this);
  45840. };
  45841. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  45842. if (!this._rigCamTransformMatrix) {
  45843. this._rigCamTransformMatrix = new BABYLON.Matrix();
  45844. }
  45845. var target = this.getTarget();
  45846. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  45847. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  45848. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  45849. };
  45850. TargetCamera.prototype.getClassName = function () {
  45851. return "TargetCamera";
  45852. };
  45853. __decorate([
  45854. BABYLON.serializeAsVector3()
  45855. ], TargetCamera.prototype, "rotation", void 0);
  45856. __decorate([
  45857. BABYLON.serialize()
  45858. ], TargetCamera.prototype, "speed", void 0);
  45859. __decorate([
  45860. BABYLON.serializeAsMeshReference("lockedTargetId")
  45861. ], TargetCamera.prototype, "lockedTarget", void 0);
  45862. return TargetCamera;
  45863. }(BABYLON.Camera));
  45864. BABYLON.TargetCamera = TargetCamera;
  45865. })(BABYLON || (BABYLON = {}));
  45866. //# sourceMappingURL=babylon.targetCamera.js.map
  45867. var BABYLON;
  45868. (function (BABYLON) {
  45869. var FreeCameraMouseInput = /** @class */ (function () {
  45870. function FreeCameraMouseInput(touchEnabled) {
  45871. if (touchEnabled === void 0) { touchEnabled = true; }
  45872. this.touchEnabled = touchEnabled;
  45873. this.buttons = [0, 1, 2];
  45874. this.angularSensibility = 2000.0;
  45875. this.previousPosition = null;
  45876. }
  45877. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  45878. var _this = this;
  45879. var engine = this.camera.getEngine();
  45880. if (!this._pointerInput) {
  45881. this._pointerInput = function (p, s) {
  45882. var evt = p.event;
  45883. if (engine.isInVRExclusivePointerMode) {
  45884. return;
  45885. }
  45886. if (!_this.touchEnabled && evt.pointerType === "touch") {
  45887. return;
  45888. }
  45889. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45890. return;
  45891. }
  45892. var srcElement = (evt.srcElement || evt.target);
  45893. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45894. try {
  45895. srcElement.setPointerCapture(evt.pointerId);
  45896. }
  45897. catch (e) {
  45898. //Nothing to do with the error. Execution will continue.
  45899. }
  45900. _this.previousPosition = {
  45901. x: evt.clientX,
  45902. y: evt.clientY
  45903. };
  45904. if (!noPreventDefault) {
  45905. evt.preventDefault();
  45906. element.focus();
  45907. }
  45908. }
  45909. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45910. try {
  45911. srcElement.releasePointerCapture(evt.pointerId);
  45912. }
  45913. catch (e) {
  45914. //Nothing to do with the error.
  45915. }
  45916. _this.previousPosition = null;
  45917. if (!noPreventDefault) {
  45918. evt.preventDefault();
  45919. }
  45920. }
  45921. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45922. if (!_this.previousPosition || engine.isPointerLock) {
  45923. return;
  45924. }
  45925. var offsetX = evt.clientX - _this.previousPosition.x;
  45926. if (_this.camera.getScene().useRightHandedSystem)
  45927. offsetX *= -1;
  45928. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45929. offsetX *= -1;
  45930. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45931. var offsetY = evt.clientY - _this.previousPosition.y;
  45932. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45933. _this.previousPosition = {
  45934. x: evt.clientX,
  45935. y: evt.clientY
  45936. };
  45937. if (!noPreventDefault) {
  45938. evt.preventDefault();
  45939. }
  45940. }
  45941. };
  45942. }
  45943. this._onMouseMove = function (evt) {
  45944. if (!engine.isPointerLock) {
  45945. return;
  45946. }
  45947. if (engine.isInVRExclusivePointerMode) {
  45948. return;
  45949. }
  45950. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  45951. if (_this.camera.getScene().useRightHandedSystem)
  45952. offsetX *= -1;
  45953. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45954. offsetX *= -1;
  45955. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45956. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  45957. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45958. _this.previousPosition = null;
  45959. if (!noPreventDefault) {
  45960. evt.preventDefault();
  45961. }
  45962. };
  45963. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  45964. element.addEventListener("mousemove", this._onMouseMove, false);
  45965. };
  45966. FreeCameraMouseInput.prototype.detachControl = function (element) {
  45967. if (this._observer && element) {
  45968. this.camera.getScene().onPointerObservable.remove(this._observer);
  45969. if (this._onMouseMove) {
  45970. element.removeEventListener("mousemove", this._onMouseMove);
  45971. }
  45972. this._observer = null;
  45973. this._onMouseMove = null;
  45974. this.previousPosition = null;
  45975. }
  45976. };
  45977. FreeCameraMouseInput.prototype.getClassName = function () {
  45978. return "FreeCameraMouseInput";
  45979. };
  45980. FreeCameraMouseInput.prototype.getSimpleName = function () {
  45981. return "mouse";
  45982. };
  45983. __decorate([
  45984. BABYLON.serialize()
  45985. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  45986. __decorate([
  45987. BABYLON.serialize()
  45988. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  45989. return FreeCameraMouseInput;
  45990. }());
  45991. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  45992. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  45993. })(BABYLON || (BABYLON = {}));
  45994. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  45995. var BABYLON;
  45996. (function (BABYLON) {
  45997. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  45998. function FreeCameraKeyboardMoveInput() {
  45999. this._keys = new Array();
  46000. this.keysUp = [38];
  46001. this.keysDown = [40];
  46002. this.keysLeft = [37];
  46003. this.keysRight = [39];
  46004. }
  46005. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46006. var _this = this;
  46007. if (this._onCanvasBlurObserver) {
  46008. return;
  46009. }
  46010. this._scene = this.camera.getScene();
  46011. this._engine = this._scene.getEngine();
  46012. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46013. _this._keys = [];
  46014. });
  46015. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46016. var evt = info.event;
  46017. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46018. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46019. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46020. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46021. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46022. var index = _this._keys.indexOf(evt.keyCode);
  46023. if (index === -1) {
  46024. _this._keys.push(evt.keyCode);
  46025. }
  46026. if (!noPreventDefault) {
  46027. evt.preventDefault();
  46028. }
  46029. }
  46030. }
  46031. else {
  46032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46035. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46036. var index = _this._keys.indexOf(evt.keyCode);
  46037. if (index >= 0) {
  46038. _this._keys.splice(index, 1);
  46039. }
  46040. if (!noPreventDefault) {
  46041. evt.preventDefault();
  46042. }
  46043. }
  46044. }
  46045. });
  46046. };
  46047. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46048. if (this._scene) {
  46049. if (this._onKeyboardObserver) {
  46050. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46051. }
  46052. if (this._onCanvasBlurObserver) {
  46053. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46054. }
  46055. this._onKeyboardObserver = null;
  46056. this._onCanvasBlurObserver = null;
  46057. }
  46058. this._keys = [];
  46059. };
  46060. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46061. if (this._onKeyboardObserver) {
  46062. var camera = this.camera;
  46063. // Keyboard
  46064. for (var index = 0; index < this._keys.length; index++) {
  46065. var keyCode = this._keys[index];
  46066. var speed = camera._computeLocalCameraSpeed();
  46067. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46068. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46069. }
  46070. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46071. camera._localDirection.copyFromFloats(0, 0, speed);
  46072. }
  46073. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46074. camera._localDirection.copyFromFloats(speed, 0, 0);
  46075. }
  46076. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46077. camera._localDirection.copyFromFloats(0, 0, -speed);
  46078. }
  46079. if (camera.getScene().useRightHandedSystem) {
  46080. camera._localDirection.z *= -1;
  46081. }
  46082. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46083. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46084. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46085. }
  46086. }
  46087. };
  46088. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46089. return "FreeCameraKeyboardMoveInput";
  46090. };
  46091. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46092. this._keys = [];
  46093. };
  46094. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46095. return "keyboard";
  46096. };
  46097. __decorate([
  46098. BABYLON.serialize()
  46099. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46100. __decorate([
  46101. BABYLON.serialize()
  46102. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46103. __decorate([
  46104. BABYLON.serialize()
  46105. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46106. __decorate([
  46107. BABYLON.serialize()
  46108. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46109. return FreeCameraKeyboardMoveInput;
  46110. }());
  46111. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46112. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46113. })(BABYLON || (BABYLON = {}));
  46114. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46115. var BABYLON;
  46116. (function (BABYLON) {
  46117. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46118. __extends(FreeCameraInputsManager, _super);
  46119. function FreeCameraInputsManager(camera) {
  46120. return _super.call(this, camera) || this;
  46121. }
  46122. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46123. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46124. return this;
  46125. };
  46126. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46127. if (touchEnabled === void 0) { touchEnabled = true; }
  46128. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46129. return this;
  46130. };
  46131. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46132. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46133. return this;
  46134. };
  46135. FreeCameraInputsManager.prototype.addTouch = function () {
  46136. this.add(new BABYLON.FreeCameraTouchInput());
  46137. return this;
  46138. };
  46139. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46140. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46141. return this;
  46142. };
  46143. return FreeCameraInputsManager;
  46144. }(BABYLON.CameraInputsManager));
  46145. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46146. })(BABYLON || (BABYLON = {}));
  46147. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46148. var BABYLON;
  46149. (function (BABYLON) {
  46150. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46151. // Forcing to use the Universal camera
  46152. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46153. });
  46154. var FreeCamera = /** @class */ (function (_super) {
  46155. __extends(FreeCamera, _super);
  46156. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46157. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46158. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46159. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46160. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46161. _this.checkCollisions = false;
  46162. _this.applyGravity = false;
  46163. _this._needMoveForGravity = false;
  46164. _this._oldPosition = BABYLON.Vector3.Zero();
  46165. _this._diffPosition = BABYLON.Vector3.Zero();
  46166. _this._newPosition = BABYLON.Vector3.Zero();
  46167. // Collisions
  46168. _this._collisionMask = -1;
  46169. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46170. if (collidedMesh === void 0) { collidedMesh = null; }
  46171. //TODO move this to the collision coordinator!
  46172. if (_this.getScene().workerCollisions)
  46173. newPosition.multiplyInPlace(_this._collider._radius);
  46174. var updatePosition = function (newPos) {
  46175. _this._newPosition.copyFrom(newPos);
  46176. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46177. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46178. _this.position.addInPlace(_this._diffPosition);
  46179. if (_this.onCollide && collidedMesh) {
  46180. _this.onCollide(collidedMesh);
  46181. }
  46182. }
  46183. };
  46184. updatePosition(newPosition);
  46185. };
  46186. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46187. _this.inputs.addKeyboard().addMouse();
  46188. return _this;
  46189. }
  46190. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46191. //-- begin properties for backward compatibility for inputs
  46192. /**
  46193. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46194. * Higher values reduce sensitivity.
  46195. */
  46196. get: function () {
  46197. var mouse = this.inputs.attached["mouse"];
  46198. if (mouse)
  46199. return mouse.angularSensibility;
  46200. return 0;
  46201. },
  46202. /**
  46203. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46204. * Higher values reduce sensitivity.
  46205. */
  46206. set: function (value) {
  46207. var mouse = this.inputs.attached["mouse"];
  46208. if (mouse)
  46209. mouse.angularSensibility = value;
  46210. },
  46211. enumerable: true,
  46212. configurable: true
  46213. });
  46214. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46215. get: function () {
  46216. var keyboard = this.inputs.attached["keyboard"];
  46217. if (keyboard)
  46218. return keyboard.keysUp;
  46219. return [];
  46220. },
  46221. set: function (value) {
  46222. var keyboard = this.inputs.attached["keyboard"];
  46223. if (keyboard)
  46224. keyboard.keysUp = value;
  46225. },
  46226. enumerable: true,
  46227. configurable: true
  46228. });
  46229. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46230. get: function () {
  46231. var keyboard = this.inputs.attached["keyboard"];
  46232. if (keyboard)
  46233. return keyboard.keysDown;
  46234. return [];
  46235. },
  46236. set: function (value) {
  46237. var keyboard = this.inputs.attached["keyboard"];
  46238. if (keyboard)
  46239. keyboard.keysDown = value;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46245. get: function () {
  46246. var keyboard = this.inputs.attached["keyboard"];
  46247. if (keyboard)
  46248. return keyboard.keysLeft;
  46249. return [];
  46250. },
  46251. set: function (value) {
  46252. var keyboard = this.inputs.attached["keyboard"];
  46253. if (keyboard)
  46254. keyboard.keysLeft = value;
  46255. },
  46256. enumerable: true,
  46257. configurable: true
  46258. });
  46259. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46260. get: function () {
  46261. var keyboard = this.inputs.attached["keyboard"];
  46262. if (keyboard)
  46263. return keyboard.keysRight;
  46264. return [];
  46265. },
  46266. set: function (value) {
  46267. var keyboard = this.inputs.attached["keyboard"];
  46268. if (keyboard)
  46269. keyboard.keysRight = value;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. // Controls
  46275. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46276. this.inputs.attachElement(element, noPreventDefault);
  46277. };
  46278. FreeCamera.prototype.detachControl = function (element) {
  46279. this.inputs.detachElement(element);
  46280. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46281. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46282. };
  46283. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46284. get: function () {
  46285. return this._collisionMask;
  46286. },
  46287. set: function (mask) {
  46288. this._collisionMask = !isNaN(mask) ? mask : -1;
  46289. },
  46290. enumerable: true,
  46291. configurable: true
  46292. });
  46293. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46294. var globalPosition;
  46295. if (this.parent) {
  46296. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46297. }
  46298. else {
  46299. globalPosition = this.position;
  46300. }
  46301. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46302. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46303. if (!this._collider) {
  46304. this._collider = new BABYLON.Collider();
  46305. }
  46306. this._collider._radius = this.ellipsoid;
  46307. this._collider.collisionMask = this._collisionMask;
  46308. //no need for clone, as long as gravity is not on.
  46309. var actualDisplacement = displacement;
  46310. //add gravity to the direction to prevent the dual-collision checking
  46311. if (this.applyGravity) {
  46312. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46313. actualDisplacement = displacement.add(this.getScene().gravity);
  46314. }
  46315. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46316. };
  46317. FreeCamera.prototype._checkInputs = function () {
  46318. if (!this._localDirection) {
  46319. this._localDirection = BABYLON.Vector3.Zero();
  46320. this._transformedDirection = BABYLON.Vector3.Zero();
  46321. }
  46322. this.inputs.checkInputs();
  46323. _super.prototype._checkInputs.call(this);
  46324. };
  46325. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46326. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46327. };
  46328. FreeCamera.prototype._updatePosition = function () {
  46329. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46330. this._collideWithWorld(this.cameraDirection);
  46331. }
  46332. else {
  46333. _super.prototype._updatePosition.call(this);
  46334. }
  46335. };
  46336. FreeCamera.prototype.dispose = function () {
  46337. this.inputs.clear();
  46338. _super.prototype.dispose.call(this);
  46339. };
  46340. FreeCamera.prototype.getClassName = function () {
  46341. return "FreeCamera";
  46342. };
  46343. __decorate([
  46344. BABYLON.serializeAsVector3()
  46345. ], FreeCamera.prototype, "ellipsoid", void 0);
  46346. __decorate([
  46347. BABYLON.serializeAsVector3()
  46348. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46349. __decorate([
  46350. BABYLON.serialize()
  46351. ], FreeCamera.prototype, "checkCollisions", void 0);
  46352. __decorate([
  46353. BABYLON.serialize()
  46354. ], FreeCamera.prototype, "applyGravity", void 0);
  46355. return FreeCamera;
  46356. }(BABYLON.TargetCamera));
  46357. BABYLON.FreeCamera = FreeCamera;
  46358. })(BABYLON || (BABYLON = {}));
  46359. //# sourceMappingURL=babylon.freeCamera.js.map
  46360. var BABYLON;
  46361. (function (BABYLON) {
  46362. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46363. function ArcRotateCameraKeyboardMoveInput() {
  46364. this._keys = new Array();
  46365. this.keysUp = [38];
  46366. this.keysDown = [40];
  46367. this.keysLeft = [37];
  46368. this.keysRight = [39];
  46369. this.keysReset = [220];
  46370. this.panningSensibility = 50.0;
  46371. this.zoomingSensibility = 25.0;
  46372. this.useAltToZoom = true;
  46373. }
  46374. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46375. var _this = this;
  46376. if (this._onCanvasBlurObserver) {
  46377. return;
  46378. }
  46379. this._scene = this.camera.getScene();
  46380. this._engine = this._scene.getEngine();
  46381. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46382. _this._keys = [];
  46383. });
  46384. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46385. var evt = info.event;
  46386. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46387. _this._ctrlPressed = evt.ctrlKey;
  46388. _this._altPressed = evt.altKey;
  46389. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46390. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46391. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46392. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46393. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46394. var index = _this._keys.indexOf(evt.keyCode);
  46395. if (index === -1) {
  46396. _this._keys.push(evt.keyCode);
  46397. }
  46398. if (evt.preventDefault) {
  46399. if (!noPreventDefault) {
  46400. evt.preventDefault();
  46401. }
  46402. }
  46403. }
  46404. }
  46405. else {
  46406. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46407. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46408. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46409. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46410. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46411. var index = _this._keys.indexOf(evt.keyCode);
  46412. if (index >= 0) {
  46413. _this._keys.splice(index, 1);
  46414. }
  46415. if (evt.preventDefault) {
  46416. if (!noPreventDefault) {
  46417. evt.preventDefault();
  46418. }
  46419. }
  46420. }
  46421. }
  46422. });
  46423. };
  46424. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46425. if (this._scene) {
  46426. if (this._onKeyboardObserver) {
  46427. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46428. }
  46429. if (this._onCanvasBlurObserver) {
  46430. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46431. }
  46432. this._onKeyboardObserver = null;
  46433. this._onCanvasBlurObserver = null;
  46434. }
  46435. this._keys = [];
  46436. };
  46437. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46438. if (this._onKeyboardObserver) {
  46439. var camera = this.camera;
  46440. for (var index = 0; index < this._keys.length; index++) {
  46441. var keyCode = this._keys[index];
  46442. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46443. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46444. camera.inertialPanningX -= 1 / this.panningSensibility;
  46445. }
  46446. else {
  46447. camera.inertialAlphaOffset -= 0.01;
  46448. }
  46449. }
  46450. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46451. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46452. camera.inertialPanningY += 1 / this.panningSensibility;
  46453. }
  46454. else if (this._altPressed && this.useAltToZoom) {
  46455. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46456. }
  46457. else {
  46458. camera.inertialBetaOffset -= 0.01;
  46459. }
  46460. }
  46461. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46462. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46463. camera.inertialPanningX += 1 / this.panningSensibility;
  46464. }
  46465. else {
  46466. camera.inertialAlphaOffset += 0.01;
  46467. }
  46468. }
  46469. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46470. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46471. camera.inertialPanningY -= 1 / this.panningSensibility;
  46472. }
  46473. else if (this._altPressed && this.useAltToZoom) {
  46474. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46475. }
  46476. else {
  46477. camera.inertialBetaOffset += 0.01;
  46478. }
  46479. }
  46480. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46481. camera.restoreState();
  46482. }
  46483. }
  46484. }
  46485. };
  46486. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46487. return "ArcRotateCameraKeyboardMoveInput";
  46488. };
  46489. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46490. return "keyboard";
  46491. };
  46492. __decorate([
  46493. BABYLON.serialize()
  46494. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46495. __decorate([
  46496. BABYLON.serialize()
  46497. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46498. __decorate([
  46499. BABYLON.serialize()
  46500. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46501. __decorate([
  46502. BABYLON.serialize()
  46503. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46504. __decorate([
  46505. BABYLON.serialize()
  46506. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46507. __decorate([
  46508. BABYLON.serialize()
  46509. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46510. __decorate([
  46511. BABYLON.serialize()
  46512. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46513. __decorate([
  46514. BABYLON.serialize()
  46515. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46516. return ArcRotateCameraKeyboardMoveInput;
  46517. }());
  46518. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46519. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46520. })(BABYLON || (BABYLON = {}));
  46521. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46522. var BABYLON;
  46523. (function (BABYLON) {
  46524. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46525. function ArcRotateCameraMouseWheelInput() {
  46526. this.wheelPrecision = 3.0;
  46527. /**
  46528. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46529. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46530. */
  46531. this.wheelDeltaPercentage = 0;
  46532. }
  46533. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46534. var _this = this;
  46535. this._wheel = function (p, s) {
  46536. //sanity check - this should be a PointerWheel event.
  46537. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46538. return;
  46539. var event = p.event;
  46540. var delta = 0;
  46541. if (event.wheelDelta) {
  46542. if (_this.wheelDeltaPercentage) {
  46543. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46544. if (event.wheelDelta > 0) {
  46545. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46546. }
  46547. else {
  46548. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46549. }
  46550. }
  46551. else {
  46552. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46553. }
  46554. }
  46555. else if (event.detail) {
  46556. delta = -event.detail / _this.wheelPrecision;
  46557. }
  46558. if (delta)
  46559. _this.camera.inertialRadiusOffset += delta;
  46560. if (event.preventDefault) {
  46561. if (!noPreventDefault) {
  46562. event.preventDefault();
  46563. }
  46564. }
  46565. };
  46566. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46567. };
  46568. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46569. if (this._observer && element) {
  46570. this.camera.getScene().onPointerObservable.remove(this._observer);
  46571. this._observer = null;
  46572. this._wheel = null;
  46573. }
  46574. };
  46575. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46576. return "ArcRotateCameraMouseWheelInput";
  46577. };
  46578. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46579. return "mousewheel";
  46580. };
  46581. __decorate([
  46582. BABYLON.serialize()
  46583. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46584. __decorate([
  46585. BABYLON.serialize()
  46586. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46587. return ArcRotateCameraMouseWheelInput;
  46588. }());
  46589. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46590. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46591. })(BABYLON || (BABYLON = {}));
  46592. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46593. var BABYLON;
  46594. (function (BABYLON) {
  46595. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46596. function ArcRotateCameraPointersInput() {
  46597. this.buttons = [0, 1, 2];
  46598. this.angularSensibilityX = 1000.0;
  46599. this.angularSensibilityY = 1000.0;
  46600. this.pinchPrecision = 12.0;
  46601. /**
  46602. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46603. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46604. */
  46605. this.pinchDeltaPercentage = 0;
  46606. this.panningSensibility = 1000.0;
  46607. this.multiTouchPanning = true;
  46608. this.multiTouchPanAndZoom = true;
  46609. this._isPanClick = false;
  46610. this.pinchInwards = true;
  46611. }
  46612. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46613. var _this = this;
  46614. var engine = this.camera.getEngine();
  46615. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46616. var pointA = null;
  46617. var pointB = null;
  46618. var previousPinchSquaredDistance = 0;
  46619. var initialDistance = 0;
  46620. var twoFingerActivityCount = 0;
  46621. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46622. this._pointerInput = function (p, s) {
  46623. var evt = p.event;
  46624. var isTouch = p.event.pointerType === "touch";
  46625. if (engine.isInVRExclusivePointerMode) {
  46626. return;
  46627. }
  46628. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46629. return;
  46630. }
  46631. var srcElement = (evt.srcElement || evt.target);
  46632. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46633. try {
  46634. srcElement.setPointerCapture(evt.pointerId);
  46635. }
  46636. catch (e) {
  46637. //Nothing to do with the error. Execution will continue.
  46638. }
  46639. // Manage panning with pan button click
  46640. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46641. // manage pointers
  46642. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46643. if (pointA === null) {
  46644. pointA = cacheSoloPointer;
  46645. }
  46646. else if (pointB === null) {
  46647. pointB = cacheSoloPointer;
  46648. }
  46649. if (!noPreventDefault) {
  46650. evt.preventDefault();
  46651. element.focus();
  46652. }
  46653. }
  46654. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46655. _this.camera.restoreState();
  46656. }
  46657. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46658. try {
  46659. srcElement.releasePointerCapture(evt.pointerId);
  46660. }
  46661. catch (e) {
  46662. //Nothing to do with the error.
  46663. }
  46664. cacheSoloPointer = null;
  46665. previousPinchSquaredDistance = 0;
  46666. previousMultiTouchPanPosition.isPaning = false;
  46667. previousMultiTouchPanPosition.isPinching = false;
  46668. twoFingerActivityCount = 0;
  46669. initialDistance = 0;
  46670. if (!isTouch) {
  46671. pointB = null; // Mouse and pen are mono pointer
  46672. }
  46673. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46674. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46675. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46676. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46677. if (engine._badOS) {
  46678. pointA = pointB = null;
  46679. }
  46680. else {
  46681. //only remove the impacted pointer in case of multitouch allowing on most
  46682. //platforms switching from rotate to zoom and pan seamlessly.
  46683. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46684. pointA = pointB;
  46685. pointB = null;
  46686. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46687. }
  46688. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46689. pointB = null;
  46690. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46691. }
  46692. else {
  46693. pointA = pointB = null;
  46694. }
  46695. }
  46696. if (!noPreventDefault) {
  46697. evt.preventDefault();
  46698. }
  46699. }
  46700. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46701. if (!noPreventDefault) {
  46702. evt.preventDefault();
  46703. }
  46704. // One button down
  46705. if (pointA && pointB === null && cacheSoloPointer) {
  46706. if (_this.panningSensibility !== 0 &&
  46707. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46708. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46709. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46710. }
  46711. else {
  46712. var offsetX = evt.clientX - cacheSoloPointer.x;
  46713. var offsetY = evt.clientY - cacheSoloPointer.y;
  46714. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46715. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46716. }
  46717. cacheSoloPointer.x = evt.clientX;
  46718. cacheSoloPointer.y = evt.clientY;
  46719. }
  46720. // Two buttons down: pinch/pan
  46721. else if (pointA && pointB) {
  46722. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46723. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46724. ed.x = evt.clientX;
  46725. ed.y = evt.clientY;
  46726. var direction = _this.pinchInwards ? 1 : -1;
  46727. var distX = pointA.x - pointB.x;
  46728. var distY = pointA.y - pointB.y;
  46729. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46730. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46731. if (previousPinchSquaredDistance === 0) {
  46732. initialDistance = pinchDistance;
  46733. previousPinchSquaredDistance = pinchSquaredDistance;
  46734. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46735. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46736. return;
  46737. }
  46738. if (_this.multiTouchPanAndZoom) {
  46739. if (_this.pinchDeltaPercentage) {
  46740. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46741. }
  46742. else {
  46743. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46744. (_this.pinchPrecision *
  46745. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46746. direction);
  46747. }
  46748. if (_this.panningSensibility !== 0) {
  46749. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46750. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46751. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46752. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46753. previousMultiTouchPanPosition.x = pointersCenterX;
  46754. previousMultiTouchPanPosition.y = pointersCenterY;
  46755. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46756. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46757. }
  46758. }
  46759. else {
  46760. twoFingerActivityCount++;
  46761. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46762. if (_this.pinchDeltaPercentage) {
  46763. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46764. }
  46765. else {
  46766. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46767. (_this.pinchPrecision *
  46768. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46769. direction);
  46770. }
  46771. previousMultiTouchPanPosition.isPaning = false;
  46772. previousMultiTouchPanPosition.isPinching = true;
  46773. }
  46774. else {
  46775. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46776. if (!previousMultiTouchPanPosition.isPaning) {
  46777. previousMultiTouchPanPosition.isPaning = true;
  46778. previousMultiTouchPanPosition.isPinching = false;
  46779. previousMultiTouchPanPosition.x = ed.x;
  46780. previousMultiTouchPanPosition.y = ed.y;
  46781. return;
  46782. }
  46783. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46784. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46785. }
  46786. }
  46787. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46788. previousMultiTouchPanPosition.x = ed.x;
  46789. previousMultiTouchPanPosition.y = ed.y;
  46790. }
  46791. }
  46792. previousPinchSquaredDistance = pinchSquaredDistance;
  46793. }
  46794. }
  46795. };
  46796. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46797. this._onContextMenu = function (evt) {
  46798. evt.preventDefault();
  46799. };
  46800. if (!this.camera._useCtrlForPanning) {
  46801. element.addEventListener("contextmenu", this._onContextMenu, false);
  46802. }
  46803. this._onLostFocus = function () {
  46804. //this._keys = [];
  46805. pointA = pointB = null;
  46806. previousPinchSquaredDistance = 0;
  46807. previousMultiTouchPanPosition.isPaning = false;
  46808. previousMultiTouchPanPosition.isPinching = false;
  46809. twoFingerActivityCount = 0;
  46810. cacheSoloPointer = null;
  46811. initialDistance = 0;
  46812. };
  46813. this._onMouseMove = function (evt) {
  46814. if (!engine.isPointerLock) {
  46815. return;
  46816. }
  46817. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46818. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46819. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46820. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46821. if (!noPreventDefault) {
  46822. evt.preventDefault();
  46823. }
  46824. };
  46825. this._onGestureStart = function (e) {
  46826. if (window.MSGesture === undefined) {
  46827. return;
  46828. }
  46829. if (!_this._MSGestureHandler) {
  46830. _this._MSGestureHandler = new MSGesture();
  46831. _this._MSGestureHandler.target = element;
  46832. }
  46833. _this._MSGestureHandler.addPointer(e.pointerId);
  46834. };
  46835. this._onGesture = function (e) {
  46836. _this.camera.radius *= e.scale;
  46837. if (e.preventDefault) {
  46838. if (!noPreventDefault) {
  46839. e.stopPropagation();
  46840. e.preventDefault();
  46841. }
  46842. }
  46843. };
  46844. element.addEventListener("mousemove", this._onMouseMove, false);
  46845. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  46846. element.addEventListener("MSGestureChange", this._onGesture, false);
  46847. BABYLON.Tools.RegisterTopRootEvents([
  46848. { name: "blur", handler: this._onLostFocus }
  46849. ]);
  46850. };
  46851. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  46852. if (this._onLostFocus) {
  46853. BABYLON.Tools.UnregisterTopRootEvents([
  46854. { name: "blur", handler: this._onLostFocus }
  46855. ]);
  46856. }
  46857. if (element && this._observer) {
  46858. this.camera.getScene().onPointerObservable.remove(this._observer);
  46859. this._observer = null;
  46860. if (this._onContextMenu) {
  46861. element.removeEventListener("contextmenu", this._onContextMenu);
  46862. }
  46863. if (this._onMouseMove) {
  46864. element.removeEventListener("mousemove", this._onMouseMove);
  46865. }
  46866. if (this._onGestureStart) {
  46867. element.removeEventListener("MSPointerDown", this._onGestureStart);
  46868. }
  46869. if (this._onGesture) {
  46870. element.removeEventListener("MSGestureChange", this._onGesture);
  46871. }
  46872. this._isPanClick = false;
  46873. this.pinchInwards = true;
  46874. this._onMouseMove = null;
  46875. this._onGestureStart = null;
  46876. this._onGesture = null;
  46877. this._MSGestureHandler = null;
  46878. this._onLostFocus = null;
  46879. this._onContextMenu = null;
  46880. }
  46881. };
  46882. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  46883. return "ArcRotateCameraPointersInput";
  46884. };
  46885. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  46886. return "pointers";
  46887. };
  46888. __decorate([
  46889. BABYLON.serialize()
  46890. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  46891. __decorate([
  46892. BABYLON.serialize()
  46893. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  46894. __decorate([
  46895. BABYLON.serialize()
  46896. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  46897. __decorate([
  46898. BABYLON.serialize()
  46899. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  46900. __decorate([
  46901. BABYLON.serialize()
  46902. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  46903. __decorate([
  46904. BABYLON.serialize()
  46905. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  46906. __decorate([
  46907. BABYLON.serialize()
  46908. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  46909. __decorate([
  46910. BABYLON.serialize()
  46911. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  46912. return ArcRotateCameraPointersInput;
  46913. }());
  46914. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  46915. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  46916. })(BABYLON || (BABYLON = {}));
  46917. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  46918. var BABYLON;
  46919. (function (BABYLON) {
  46920. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  46921. __extends(ArcRotateCameraInputsManager, _super);
  46922. function ArcRotateCameraInputsManager(camera) {
  46923. return _super.call(this, camera) || this;
  46924. }
  46925. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  46926. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  46927. return this;
  46928. };
  46929. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  46930. this.add(new BABYLON.ArcRotateCameraPointersInput());
  46931. return this;
  46932. };
  46933. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  46934. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  46935. return this;
  46936. };
  46937. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  46938. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  46939. return this;
  46940. };
  46941. return ArcRotateCameraInputsManager;
  46942. }(BABYLON.CameraInputsManager));
  46943. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  46944. })(BABYLON || (BABYLON = {}));
  46945. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  46946. var BABYLON;
  46947. (function (BABYLON) {
  46948. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  46949. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  46950. });
  46951. var ArcRotateCamera = /** @class */ (function (_super) {
  46952. __extends(ArcRotateCamera, _super);
  46953. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  46954. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46955. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  46956. _this.inertialAlphaOffset = 0;
  46957. _this.inertialBetaOffset = 0;
  46958. _this.inertialRadiusOffset = 0;
  46959. _this.lowerAlphaLimit = null;
  46960. _this.upperAlphaLimit = null;
  46961. _this.lowerBetaLimit = 0.01;
  46962. _this.upperBetaLimit = Math.PI;
  46963. _this.lowerRadiusLimit = null;
  46964. _this.upperRadiusLimit = null;
  46965. _this.inertialPanningX = 0;
  46966. _this.inertialPanningY = 0;
  46967. _this.pinchToPanMaxDistance = 20;
  46968. _this.panningDistanceLimit = null;
  46969. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  46970. _this.panningInertia = 0.9;
  46971. //-- end properties for backward compatibility for inputs
  46972. _this.zoomOnFactor = 1;
  46973. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  46974. _this.allowUpsideDown = true;
  46975. _this._viewMatrix = new BABYLON.Matrix();
  46976. // Panning
  46977. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  46978. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  46979. _this.checkCollisions = false;
  46980. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46981. _this._previousPosition = BABYLON.Vector3.Zero();
  46982. _this._collisionVelocity = BABYLON.Vector3.Zero();
  46983. _this._newPosition = BABYLON.Vector3.Zero();
  46984. _this._computationVector = BABYLON.Vector3.Zero();
  46985. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46986. if (collidedMesh === void 0) { collidedMesh = null; }
  46987. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  46988. newPosition.multiplyInPlace(_this._collider._radius);
  46989. }
  46990. if (!collidedMesh) {
  46991. _this._previousPosition.copyFrom(_this.position);
  46992. }
  46993. else {
  46994. _this.setPosition(newPosition);
  46995. if (_this.onCollide) {
  46996. _this.onCollide(collidedMesh);
  46997. }
  46998. }
  46999. // Recompute because of constraints
  47000. var cosa = Math.cos(_this.alpha);
  47001. var sina = Math.sin(_this.alpha);
  47002. var cosb = Math.cos(_this.beta);
  47003. var sinb = Math.sin(_this.beta);
  47004. if (sinb === 0) {
  47005. sinb = 0.0001;
  47006. }
  47007. var target = _this._getTargetPosition();
  47008. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47009. target.addToRef(_this._computationVector, _this._newPosition);
  47010. _this.position.copyFrom(_this._newPosition);
  47011. var up = _this.upVector;
  47012. if (_this.allowUpsideDown && _this.beta < 0) {
  47013. up = up.clone();
  47014. up = up.negate();
  47015. }
  47016. _this._computeViewMatrix(_this.position, target, up);
  47017. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47018. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47019. _this._collisionTriggered = false;
  47020. };
  47021. _this._target = BABYLON.Vector3.Zero();
  47022. if (target) {
  47023. _this.setTarget(target);
  47024. }
  47025. _this.alpha = alpha;
  47026. _this.beta = beta;
  47027. _this.radius = radius;
  47028. _this.getViewMatrix();
  47029. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47030. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47031. return _this;
  47032. }
  47033. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47034. get: function () {
  47035. return this._target;
  47036. },
  47037. set: function (value) {
  47038. this.setTarget(value);
  47039. },
  47040. enumerable: true,
  47041. configurable: true
  47042. });
  47043. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47044. //-- begin properties for backward compatibility for inputs
  47045. get: function () {
  47046. var pointers = this.inputs.attached["pointers"];
  47047. if (pointers)
  47048. return pointers.angularSensibilityX;
  47049. return 0;
  47050. },
  47051. set: function (value) {
  47052. var pointers = this.inputs.attached["pointers"];
  47053. if (pointers) {
  47054. pointers.angularSensibilityX = value;
  47055. }
  47056. },
  47057. enumerable: true,
  47058. configurable: true
  47059. });
  47060. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47061. get: function () {
  47062. var pointers = this.inputs.attached["pointers"];
  47063. if (pointers)
  47064. return pointers.angularSensibilityY;
  47065. return 0;
  47066. },
  47067. set: function (value) {
  47068. var pointers = this.inputs.attached["pointers"];
  47069. if (pointers) {
  47070. pointers.angularSensibilityY = value;
  47071. }
  47072. },
  47073. enumerable: true,
  47074. configurable: true
  47075. });
  47076. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47077. get: function () {
  47078. var pointers = this.inputs.attached["pointers"];
  47079. if (pointers)
  47080. return pointers.pinchPrecision;
  47081. return 0;
  47082. },
  47083. set: function (value) {
  47084. var pointers = this.inputs.attached["pointers"];
  47085. if (pointers) {
  47086. pointers.pinchPrecision = value;
  47087. }
  47088. },
  47089. enumerable: true,
  47090. configurable: true
  47091. });
  47092. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47093. get: function () {
  47094. var pointers = this.inputs.attached["pointers"];
  47095. if (pointers)
  47096. return pointers.pinchDeltaPercentage;
  47097. return 0;
  47098. },
  47099. set: function (value) {
  47100. var pointers = this.inputs.attached["pointers"];
  47101. if (pointers) {
  47102. pointers.pinchDeltaPercentage = value;
  47103. }
  47104. },
  47105. enumerable: true,
  47106. configurable: true
  47107. });
  47108. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47109. get: function () {
  47110. var pointers = this.inputs.attached["pointers"];
  47111. if (pointers)
  47112. return pointers.panningSensibility;
  47113. return 0;
  47114. },
  47115. set: function (value) {
  47116. var pointers = this.inputs.attached["pointers"];
  47117. if (pointers) {
  47118. pointers.panningSensibility = value;
  47119. }
  47120. },
  47121. enumerable: true,
  47122. configurable: true
  47123. });
  47124. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47125. get: function () {
  47126. var keyboard = this.inputs.attached["keyboard"];
  47127. if (keyboard)
  47128. return keyboard.keysUp;
  47129. return [];
  47130. },
  47131. set: function (value) {
  47132. var keyboard = this.inputs.attached["keyboard"];
  47133. if (keyboard)
  47134. keyboard.keysUp = value;
  47135. },
  47136. enumerable: true,
  47137. configurable: true
  47138. });
  47139. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47140. get: function () {
  47141. var keyboard = this.inputs.attached["keyboard"];
  47142. if (keyboard)
  47143. return keyboard.keysDown;
  47144. return [];
  47145. },
  47146. set: function (value) {
  47147. var keyboard = this.inputs.attached["keyboard"];
  47148. if (keyboard)
  47149. keyboard.keysDown = value;
  47150. },
  47151. enumerable: true,
  47152. configurable: true
  47153. });
  47154. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47155. get: function () {
  47156. var keyboard = this.inputs.attached["keyboard"];
  47157. if (keyboard)
  47158. return keyboard.keysLeft;
  47159. return [];
  47160. },
  47161. set: function (value) {
  47162. var keyboard = this.inputs.attached["keyboard"];
  47163. if (keyboard)
  47164. keyboard.keysLeft = value;
  47165. },
  47166. enumerable: true,
  47167. configurable: true
  47168. });
  47169. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47170. get: function () {
  47171. var keyboard = this.inputs.attached["keyboard"];
  47172. if (keyboard)
  47173. return keyboard.keysRight;
  47174. return [];
  47175. },
  47176. set: function (value) {
  47177. var keyboard = this.inputs.attached["keyboard"];
  47178. if (keyboard)
  47179. keyboard.keysRight = value;
  47180. },
  47181. enumerable: true,
  47182. configurable: true
  47183. });
  47184. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47185. get: function () {
  47186. var mousewheel = this.inputs.attached["mousewheel"];
  47187. if (mousewheel)
  47188. return mousewheel.wheelPrecision;
  47189. return 0;
  47190. },
  47191. set: function (value) {
  47192. var mousewheel = this.inputs.attached["mousewheel"];
  47193. if (mousewheel)
  47194. mousewheel.wheelPrecision = value;
  47195. },
  47196. enumerable: true,
  47197. configurable: true
  47198. });
  47199. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47200. get: function () {
  47201. var mousewheel = this.inputs.attached["mousewheel"];
  47202. if (mousewheel)
  47203. return mousewheel.wheelDeltaPercentage;
  47204. return 0;
  47205. },
  47206. set: function (value) {
  47207. var mousewheel = this.inputs.attached["mousewheel"];
  47208. if (mousewheel)
  47209. mousewheel.wheelDeltaPercentage = value;
  47210. },
  47211. enumerable: true,
  47212. configurable: true
  47213. });
  47214. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47215. get: function () {
  47216. return this._bouncingBehavior;
  47217. },
  47218. enumerable: true,
  47219. configurable: true
  47220. });
  47221. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47222. get: function () {
  47223. return this._bouncingBehavior != null;
  47224. },
  47225. set: function (value) {
  47226. if (value === this.useBouncingBehavior) {
  47227. return;
  47228. }
  47229. if (value) {
  47230. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47231. this.addBehavior(this._bouncingBehavior);
  47232. }
  47233. else if (this._bouncingBehavior) {
  47234. this.removeBehavior(this._bouncingBehavior);
  47235. this._bouncingBehavior = null;
  47236. }
  47237. },
  47238. enumerable: true,
  47239. configurable: true
  47240. });
  47241. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47242. get: function () {
  47243. return this._framingBehavior;
  47244. },
  47245. enumerable: true,
  47246. configurable: true
  47247. });
  47248. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47249. get: function () {
  47250. return this._framingBehavior != null;
  47251. },
  47252. set: function (value) {
  47253. if (value === this.useFramingBehavior) {
  47254. return;
  47255. }
  47256. if (value) {
  47257. this._framingBehavior = new BABYLON.FramingBehavior();
  47258. this.addBehavior(this._framingBehavior);
  47259. }
  47260. else if (this._framingBehavior) {
  47261. this.removeBehavior(this._framingBehavior);
  47262. this._framingBehavior = null;
  47263. }
  47264. },
  47265. enumerable: true,
  47266. configurable: true
  47267. });
  47268. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47269. get: function () {
  47270. return this._autoRotationBehavior;
  47271. },
  47272. enumerable: true,
  47273. configurable: true
  47274. });
  47275. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47276. get: function () {
  47277. return this._autoRotationBehavior != null;
  47278. },
  47279. set: function (value) {
  47280. if (value === this.useAutoRotationBehavior) {
  47281. return;
  47282. }
  47283. if (value) {
  47284. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47285. this.addBehavior(this._autoRotationBehavior);
  47286. }
  47287. else if (this._autoRotationBehavior) {
  47288. this.removeBehavior(this._autoRotationBehavior);
  47289. this._autoRotationBehavior = null;
  47290. }
  47291. },
  47292. enumerable: true,
  47293. configurable: true
  47294. });
  47295. // Cache
  47296. ArcRotateCamera.prototype._initCache = function () {
  47297. _super.prototype._initCache.call(this);
  47298. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47299. this._cache.alpha = undefined;
  47300. this._cache.beta = undefined;
  47301. this._cache.radius = undefined;
  47302. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47303. };
  47304. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47305. if (!ignoreParentClass) {
  47306. _super.prototype._updateCache.call(this);
  47307. }
  47308. this._cache._target.copyFrom(this._getTargetPosition());
  47309. this._cache.alpha = this.alpha;
  47310. this._cache.beta = this.beta;
  47311. this._cache.radius = this.radius;
  47312. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47313. };
  47314. ArcRotateCamera.prototype._getTargetPosition = function () {
  47315. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47316. var pos = this._targetHost.getAbsolutePosition();
  47317. if (this._targetBoundingCenter) {
  47318. pos.addToRef(this._targetBoundingCenter, this._target);
  47319. }
  47320. else {
  47321. this._target.copyFrom(pos);
  47322. }
  47323. }
  47324. var lockedTargetPosition = this._getLockedTargetPosition();
  47325. if (lockedTargetPosition) {
  47326. return lockedTargetPosition;
  47327. }
  47328. return this._target;
  47329. };
  47330. ArcRotateCamera.prototype.storeState = function () {
  47331. this._storedAlpha = this.alpha;
  47332. this._storedBeta = this.beta;
  47333. this._storedRadius = this.radius;
  47334. this._storedTarget = this._getTargetPosition().clone();
  47335. return _super.prototype.storeState.call(this);
  47336. };
  47337. /**
  47338. * Restored camera state. You must call storeState() first
  47339. */
  47340. ArcRotateCamera.prototype._restoreStateValues = function () {
  47341. if (!_super.prototype._restoreStateValues.call(this)) {
  47342. return false;
  47343. }
  47344. this.alpha = this._storedAlpha;
  47345. this.beta = this._storedBeta;
  47346. this.radius = this._storedRadius;
  47347. this.setTarget(this._storedTarget.clone());
  47348. this.inertialAlphaOffset = 0;
  47349. this.inertialBetaOffset = 0;
  47350. this.inertialRadiusOffset = 0;
  47351. this.inertialPanningX = 0;
  47352. this.inertialPanningY = 0;
  47353. return true;
  47354. };
  47355. // Synchronized
  47356. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47357. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47358. return false;
  47359. return this._cache._target.equals(this._getTargetPosition())
  47360. && this._cache.alpha === this.alpha
  47361. && this._cache.beta === this.beta
  47362. && this._cache.radius === this.radius
  47363. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47364. };
  47365. // Methods
  47366. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47367. var _this = this;
  47368. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47369. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47370. this._useCtrlForPanning = useCtrlForPanning;
  47371. this._panningMouseButton = panningMouseButton;
  47372. this.inputs.attachElement(element, noPreventDefault);
  47373. this._reset = function () {
  47374. _this.inertialAlphaOffset = 0;
  47375. _this.inertialBetaOffset = 0;
  47376. _this.inertialRadiusOffset = 0;
  47377. _this.inertialPanningX = 0;
  47378. _this.inertialPanningY = 0;
  47379. };
  47380. };
  47381. ArcRotateCamera.prototype.detachControl = function (element) {
  47382. this.inputs.detachElement(element);
  47383. if (this._reset) {
  47384. this._reset();
  47385. }
  47386. };
  47387. ArcRotateCamera.prototype._checkInputs = function () {
  47388. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47389. if (this._collisionTriggered) {
  47390. return;
  47391. }
  47392. this.inputs.checkInputs();
  47393. // Inertia
  47394. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47395. var inertialAlphaOffset = this.inertialAlphaOffset;
  47396. if (this.beta <= 0)
  47397. inertialAlphaOffset *= -1;
  47398. if (this.getScene().useRightHandedSystem)
  47399. inertialAlphaOffset *= -1;
  47400. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47401. inertialAlphaOffset *= -1;
  47402. this.alpha += inertialAlphaOffset;
  47403. this.beta += this.inertialBetaOffset;
  47404. this.radius -= this.inertialRadiusOffset;
  47405. this.inertialAlphaOffset *= this.inertia;
  47406. this.inertialBetaOffset *= this.inertia;
  47407. this.inertialRadiusOffset *= this.inertia;
  47408. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47409. this.inertialAlphaOffset = 0;
  47410. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47411. this.inertialBetaOffset = 0;
  47412. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47413. this.inertialRadiusOffset = 0;
  47414. }
  47415. // Panning inertia
  47416. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47417. if (!this._localDirection) {
  47418. this._localDirection = BABYLON.Vector3.Zero();
  47419. this._transformedDirection = BABYLON.Vector3.Zero();
  47420. }
  47421. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47422. this._localDirection.multiplyInPlace(this.panningAxis);
  47423. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47424. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47425. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47426. if (!this.panningAxis.y) {
  47427. this._transformedDirection.y = 0;
  47428. }
  47429. if (!this._targetHost) {
  47430. if (this.panningDistanceLimit) {
  47431. this._transformedDirection.addInPlace(this._target);
  47432. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47433. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47434. this._target.copyFrom(this._transformedDirection);
  47435. }
  47436. }
  47437. else {
  47438. this._target.addInPlace(this._transformedDirection);
  47439. }
  47440. }
  47441. this.inertialPanningX *= this.panningInertia;
  47442. this.inertialPanningY *= this.panningInertia;
  47443. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47444. this.inertialPanningX = 0;
  47445. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47446. this.inertialPanningY = 0;
  47447. }
  47448. // Limits
  47449. this._checkLimits();
  47450. _super.prototype._checkInputs.call(this);
  47451. };
  47452. ArcRotateCamera.prototype._checkLimits = function () {
  47453. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47454. if (this.allowUpsideDown && this.beta > Math.PI) {
  47455. this.beta = this.beta - (2 * Math.PI);
  47456. }
  47457. }
  47458. else {
  47459. if (this.beta < this.lowerBetaLimit) {
  47460. this.beta = this.lowerBetaLimit;
  47461. }
  47462. }
  47463. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47464. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47465. this.beta = this.beta + (2 * Math.PI);
  47466. }
  47467. }
  47468. else {
  47469. if (this.beta > this.upperBetaLimit) {
  47470. this.beta = this.upperBetaLimit;
  47471. }
  47472. }
  47473. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47474. this.alpha = this.lowerAlphaLimit;
  47475. }
  47476. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47477. this.alpha = this.upperAlphaLimit;
  47478. }
  47479. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47480. this.radius = this.lowerRadiusLimit;
  47481. }
  47482. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47483. this.radius = this.upperRadiusLimit;
  47484. }
  47485. };
  47486. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47487. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47488. this.radius = this._computationVector.length();
  47489. if (this.radius === 0) {
  47490. this.radius = 0.0001; // Just to avoid division by zero
  47491. }
  47492. // Alpha
  47493. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47494. if (this._computationVector.z < 0) {
  47495. this.alpha = 2 * Math.PI - this.alpha;
  47496. }
  47497. // Beta
  47498. this.beta = Math.acos(this._computationVector.y / this.radius);
  47499. this._checkLimits();
  47500. };
  47501. ArcRotateCamera.prototype.setPosition = function (position) {
  47502. if (this.position.equals(position)) {
  47503. return;
  47504. }
  47505. this.position.copyFrom(position);
  47506. this.rebuildAnglesAndRadius();
  47507. };
  47508. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47509. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47510. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47511. if (target.getBoundingInfo) {
  47512. if (toBoundingCenter) {
  47513. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47514. }
  47515. else {
  47516. this._targetBoundingCenter = null;
  47517. }
  47518. this._targetHost = target;
  47519. this._target = this._getTargetPosition();
  47520. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47521. }
  47522. else {
  47523. var newTarget = target;
  47524. var currentTarget = this._getTargetPosition();
  47525. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47526. return;
  47527. }
  47528. this._targetHost = null;
  47529. this._target = newTarget;
  47530. this._targetBoundingCenter = null;
  47531. this.onMeshTargetChangedObservable.notifyObservers(null);
  47532. }
  47533. this.rebuildAnglesAndRadius();
  47534. };
  47535. ArcRotateCamera.prototype._getViewMatrix = function () {
  47536. // Compute
  47537. var cosa = Math.cos(this.alpha);
  47538. var sina = Math.sin(this.alpha);
  47539. var cosb = Math.cos(this.beta);
  47540. var sinb = Math.sin(this.beta);
  47541. if (sinb === 0) {
  47542. sinb = 0.0001;
  47543. }
  47544. var target = this._getTargetPosition();
  47545. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47546. target.addToRef(this._computationVector, this._newPosition);
  47547. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47548. if (!this._collider) {
  47549. this._collider = new BABYLON.Collider();
  47550. }
  47551. this._collider._radius = this.collisionRadius;
  47552. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47553. this._collisionTriggered = true;
  47554. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47555. }
  47556. else {
  47557. this.position.copyFrom(this._newPosition);
  47558. var up = this.upVector;
  47559. if (this.allowUpsideDown && sinb < 0) {
  47560. up = up.clone();
  47561. up = up.negate();
  47562. }
  47563. this._computeViewMatrix(this.position, target, up);
  47564. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47565. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47566. }
  47567. this._currentTarget = target;
  47568. return this._viewMatrix;
  47569. };
  47570. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47571. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47572. meshes = meshes || this.getScene().meshes;
  47573. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47574. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47575. this.radius = distance * this.zoomOnFactor;
  47576. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47577. };
  47578. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47579. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47580. var meshesOrMinMaxVector;
  47581. var distance;
  47582. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47583. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47584. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47585. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47586. }
  47587. else { //minMaxVector and distance
  47588. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47589. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47590. distance = minMaxVectorAndDistance.distance;
  47591. }
  47592. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47593. if (!doNotUpdateMaxZ) {
  47594. this.maxZ = distance * 2;
  47595. }
  47596. };
  47597. /**
  47598. * @override
  47599. * Override Camera.createRigCamera
  47600. */
  47601. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47602. var alphaShift = 0;
  47603. switch (this.cameraRigMode) {
  47604. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47605. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47606. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47607. case BABYLON.Camera.RIG_MODE_VR:
  47608. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47609. break;
  47610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47611. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47612. break;
  47613. }
  47614. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47615. rigCam._cameraRigParams = {};
  47616. return rigCam;
  47617. };
  47618. /**
  47619. * @override
  47620. * Override Camera._updateRigCameras
  47621. */
  47622. ArcRotateCamera.prototype._updateRigCameras = function () {
  47623. var camLeft = this._rigCameras[0];
  47624. var camRight = this._rigCameras[1];
  47625. camLeft.beta = camRight.beta = this.beta;
  47626. camLeft.radius = camRight.radius = this.radius;
  47627. switch (this.cameraRigMode) {
  47628. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47629. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47631. case BABYLON.Camera.RIG_MODE_VR:
  47632. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47633. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47634. break;
  47635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47636. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47637. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47638. break;
  47639. }
  47640. _super.prototype._updateRigCameras.call(this);
  47641. };
  47642. ArcRotateCamera.prototype.dispose = function () {
  47643. this.inputs.clear();
  47644. _super.prototype.dispose.call(this);
  47645. };
  47646. ArcRotateCamera.prototype.getClassName = function () {
  47647. return "ArcRotateCamera";
  47648. };
  47649. __decorate([
  47650. BABYLON.serialize()
  47651. ], ArcRotateCamera.prototype, "alpha", void 0);
  47652. __decorate([
  47653. BABYLON.serialize()
  47654. ], ArcRotateCamera.prototype, "beta", void 0);
  47655. __decorate([
  47656. BABYLON.serialize()
  47657. ], ArcRotateCamera.prototype, "radius", void 0);
  47658. __decorate([
  47659. BABYLON.serializeAsVector3("target")
  47660. ], ArcRotateCamera.prototype, "_target", void 0);
  47661. __decorate([
  47662. BABYLON.serialize()
  47663. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47664. __decorate([
  47665. BABYLON.serialize()
  47666. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47667. __decorate([
  47668. BABYLON.serialize()
  47669. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47670. __decorate([
  47671. BABYLON.serialize()
  47672. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47673. __decorate([
  47674. BABYLON.serialize()
  47675. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47676. __decorate([
  47677. BABYLON.serialize()
  47678. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47679. __decorate([
  47680. BABYLON.serialize()
  47681. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47682. __decorate([
  47683. BABYLON.serialize()
  47684. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47685. __decorate([
  47686. BABYLON.serialize()
  47687. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47688. __decorate([
  47689. BABYLON.serialize()
  47690. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47691. __decorate([
  47692. BABYLON.serialize()
  47693. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47694. __decorate([
  47695. BABYLON.serialize()
  47696. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47697. __decorate([
  47698. BABYLON.serialize()
  47699. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47700. __decorate([
  47701. BABYLON.serializeAsVector3()
  47702. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47703. __decorate([
  47704. BABYLON.serialize()
  47705. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47706. __decorate([
  47707. BABYLON.serialize()
  47708. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47709. __decorate([
  47710. BABYLON.serialize()
  47711. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47712. return ArcRotateCamera;
  47713. }(BABYLON.TargetCamera));
  47714. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47715. })(BABYLON || (BABYLON = {}));
  47716. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47717. var BABYLON;
  47718. (function (BABYLON) {
  47719. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  47720. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  47721. });
  47722. /**
  47723. * The HemisphericLight simulates the ambient environment light,
  47724. * so the passed direction is the light reflection direction, not the incoming direction.
  47725. */
  47726. var HemisphericLight = /** @class */ (function (_super) {
  47727. __extends(HemisphericLight, _super);
  47728. /**
  47729. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47730. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47731. * The HemisphericLight can't cast shadows.
  47732. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47733. * @param name The friendly name of the light
  47734. * @param direction The direction of the light reflection
  47735. * @param scene The scene the light belongs to
  47736. */
  47737. function HemisphericLight(name, direction, scene) {
  47738. var _this = _super.call(this, name, scene) || this;
  47739. /**
  47740. * The groundColor is the light in the opposite direction to the one specified during creation.
  47741. * 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.
  47742. */
  47743. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47744. _this.direction = direction || BABYLON.Vector3.Up();
  47745. return _this;
  47746. }
  47747. HemisphericLight.prototype._buildUniformLayout = function () {
  47748. this._uniformBuffer.addUniform("vLightData", 4);
  47749. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47750. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47751. this._uniformBuffer.addUniform("vLightGround", 3);
  47752. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47753. this._uniformBuffer.addUniform("depthValues", 2);
  47754. this._uniformBuffer.create();
  47755. };
  47756. /**
  47757. * Returns the string "HemisphericLight".
  47758. * @return The class name
  47759. */
  47760. HemisphericLight.prototype.getClassName = function () {
  47761. return "HemisphericLight";
  47762. };
  47763. /**
  47764. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47765. * Returns the updated direction.
  47766. * @param target The target the direction should point to
  47767. * @return The computed direction
  47768. */
  47769. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47770. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47771. return this.direction;
  47772. };
  47773. /**
  47774. * Returns the shadow generator associated to the light.
  47775. * @returns Always null for hemispheric lights because it does not support shadows.
  47776. */
  47777. HemisphericLight.prototype.getShadowGenerator = function () {
  47778. return null;
  47779. };
  47780. /**
  47781. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47782. * @param effect The effect to update
  47783. * @param lightIndex The index of the light in the effect to update
  47784. * @returns The hemispheric light
  47785. */
  47786. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47787. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47788. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47789. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47790. return this;
  47791. };
  47792. /**
  47793. * @hidden internal use only.
  47794. */
  47795. HemisphericLight.prototype._getWorldMatrix = function () {
  47796. if (!this._worldMatrix) {
  47797. this._worldMatrix = BABYLON.Matrix.Identity();
  47798. }
  47799. return this._worldMatrix;
  47800. };
  47801. /**
  47802. * Returns the integer 3.
  47803. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47804. */
  47805. HemisphericLight.prototype.getTypeID = function () {
  47806. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47807. };
  47808. /**
  47809. * Prepares the list of defines specific to the light type.
  47810. * @param defines the list of defines
  47811. * @param lightIndex defines the index of the light for the effect
  47812. */
  47813. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  47814. defines["HEMILIGHT" + lightIndex] = true;
  47815. };
  47816. __decorate([
  47817. BABYLON.serializeAsColor3()
  47818. ], HemisphericLight.prototype, "groundColor", void 0);
  47819. __decorate([
  47820. BABYLON.serializeAsVector3()
  47821. ], HemisphericLight.prototype, "direction", void 0);
  47822. return HemisphericLight;
  47823. }(BABYLON.Light));
  47824. BABYLON.HemisphericLight = HemisphericLight;
  47825. })(BABYLON || (BABYLON = {}));
  47826. //# sourceMappingURL=babylon.hemisphericLight.js.map
  47827. var BABYLON;
  47828. (function (BABYLON) {
  47829. /**
  47830. * Base implementation IShadowLight
  47831. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  47832. */
  47833. var ShadowLight = /** @class */ (function (_super) {
  47834. __extends(ShadowLight, _super);
  47835. function ShadowLight() {
  47836. var _this = _super !== null && _super.apply(this, arguments) || this;
  47837. _this._needProjectionMatrixCompute = true;
  47838. return _this;
  47839. }
  47840. ShadowLight.prototype._setPosition = function (value) {
  47841. this._position = value;
  47842. };
  47843. Object.defineProperty(ShadowLight.prototype, "position", {
  47844. /**
  47845. * Sets the position the shadow will be casted from. Also use as the light position for both
  47846. * point and spot lights.
  47847. */
  47848. get: function () {
  47849. return this._position;
  47850. },
  47851. /**
  47852. * Sets the position the shadow will be casted from. Also use as the light position for both
  47853. * point and spot lights.
  47854. */
  47855. set: function (value) {
  47856. this._setPosition(value);
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. ShadowLight.prototype._setDirection = function (value) {
  47862. this._direction = value;
  47863. };
  47864. Object.defineProperty(ShadowLight.prototype, "direction", {
  47865. /**
  47866. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  47867. * Also use as the light direction on spot and directional lights.
  47868. */
  47869. get: function () {
  47870. return this._direction;
  47871. },
  47872. /**
  47873. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  47874. * Also use as the light direction on spot and directional lights.
  47875. */
  47876. set: function (value) {
  47877. this._setDirection(value);
  47878. },
  47879. enumerable: true,
  47880. configurable: true
  47881. });
  47882. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  47883. /**
  47884. * Gets the shadow projection clipping minimum z value.
  47885. */
  47886. get: function () {
  47887. return this._shadowMinZ;
  47888. },
  47889. /**
  47890. * Sets the shadow projection clipping minimum z value.
  47891. */
  47892. set: function (value) {
  47893. this._shadowMinZ = value;
  47894. this.forceProjectionMatrixCompute();
  47895. },
  47896. enumerable: true,
  47897. configurable: true
  47898. });
  47899. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  47900. /**
  47901. * Sets the shadow projection clipping maximum z value.
  47902. */
  47903. get: function () {
  47904. return this._shadowMaxZ;
  47905. },
  47906. /**
  47907. * Gets the shadow projection clipping maximum z value.
  47908. */
  47909. set: function (value) {
  47910. this._shadowMaxZ = value;
  47911. this.forceProjectionMatrixCompute();
  47912. },
  47913. enumerable: true,
  47914. configurable: true
  47915. });
  47916. /**
  47917. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  47918. * @returns true if the information has been computed, false if it does not need to (no parenting)
  47919. */
  47920. ShadowLight.prototype.computeTransformedInformation = function () {
  47921. if (this.parent && this.parent.getWorldMatrix) {
  47922. if (!this.transformedPosition) {
  47923. this.transformedPosition = BABYLON.Vector3.Zero();
  47924. }
  47925. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  47926. // In case the direction is present.
  47927. if (this.direction) {
  47928. if (!this.transformedDirection) {
  47929. this.transformedDirection = BABYLON.Vector3.Zero();
  47930. }
  47931. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  47932. }
  47933. return true;
  47934. }
  47935. return false;
  47936. };
  47937. /**
  47938. * Return the depth scale used for the shadow map.
  47939. * @returns the depth scale.
  47940. */
  47941. ShadowLight.prototype.getDepthScale = function () {
  47942. return 50.0;
  47943. };
  47944. /**
  47945. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  47946. * @param faceIndex The index of the face we are computed the direction to generate shadow
  47947. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  47948. */
  47949. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  47950. return this.transformedDirection ? this.transformedDirection : this.direction;
  47951. };
  47952. /**
  47953. * Returns the ShadowLight absolute position in the World.
  47954. * @returns the position vector in world space
  47955. */
  47956. ShadowLight.prototype.getAbsolutePosition = function () {
  47957. return this.transformedPosition ? this.transformedPosition : this.position;
  47958. };
  47959. /**
  47960. * Sets the ShadowLight direction toward the passed target.
  47961. * @param target The point tot target in local space
  47962. * @returns the updated ShadowLight direction
  47963. */
  47964. ShadowLight.prototype.setDirectionToTarget = function (target) {
  47965. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  47966. return this.direction;
  47967. };
  47968. /**
  47969. * Returns the light rotation in euler definition.
  47970. * @returns the x y z rotation in local space.
  47971. */
  47972. ShadowLight.prototype.getRotation = function () {
  47973. this.direction.normalize();
  47974. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  47975. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  47976. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  47977. };
  47978. /**
  47979. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  47980. * @returns true if a cube texture needs to be use
  47981. */
  47982. ShadowLight.prototype.needCube = function () {
  47983. return false;
  47984. };
  47985. /**
  47986. * Detects if the projection matrix requires to be recomputed this frame.
  47987. * @returns true if it requires to be recomputed otherwise, false.
  47988. */
  47989. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  47990. return this._needProjectionMatrixCompute;
  47991. };
  47992. /**
  47993. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  47994. */
  47995. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  47996. this._needProjectionMatrixCompute = true;
  47997. };
  47998. /**
  47999. * Get the world matrix of the sahdow lights.
  48000. * @hidden Internal Use Only
  48001. */
  48002. ShadowLight.prototype._getWorldMatrix = function () {
  48003. if (!this._worldMatrix) {
  48004. this._worldMatrix = BABYLON.Matrix.Identity();
  48005. }
  48006. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48007. return this._worldMatrix;
  48008. };
  48009. /**
  48010. * Gets the minZ used for shadow according to both the scene and the light.
  48011. * @param activeCamera The camera we are returning the min for
  48012. * @returns the depth min z
  48013. */
  48014. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48015. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48016. };
  48017. /**
  48018. * Gets the maxZ used for shadow according to both the scene and the light.
  48019. * @param activeCamera The camera we are returning the max for
  48020. * @returns the depth max z
  48021. */
  48022. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48023. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48024. };
  48025. /**
  48026. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48027. * @param matrix The materix to updated with the projection information
  48028. * @param viewMatrix The transform matrix of the light
  48029. * @param renderList The list of mesh to render in the map
  48030. * @returns The current light
  48031. */
  48032. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48033. if (this.customProjectionMatrixBuilder) {
  48034. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48035. }
  48036. else {
  48037. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48038. }
  48039. return this;
  48040. };
  48041. __decorate([
  48042. BABYLON.serializeAsVector3()
  48043. ], ShadowLight.prototype, "position", null);
  48044. __decorate([
  48045. BABYLON.serializeAsVector3()
  48046. ], ShadowLight.prototype, "direction", null);
  48047. __decorate([
  48048. BABYLON.serialize()
  48049. ], ShadowLight.prototype, "shadowMinZ", null);
  48050. __decorate([
  48051. BABYLON.serialize()
  48052. ], ShadowLight.prototype, "shadowMaxZ", null);
  48053. return ShadowLight;
  48054. }(BABYLON.Light));
  48055. BABYLON.ShadowLight = ShadowLight;
  48056. })(BABYLON || (BABYLON = {}));
  48057. //# sourceMappingURL=babylon.shadowLight.js.map
  48058. var BABYLON;
  48059. (function (BABYLON) {
  48060. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48061. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48062. });
  48063. /**
  48064. * A point light is a light defined by an unique point in world space.
  48065. * The light is emitted in every direction from this point.
  48066. * A good example of a point light is a standard light bulb.
  48067. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48068. */
  48069. var PointLight = /** @class */ (function (_super) {
  48070. __extends(PointLight, _super);
  48071. /**
  48072. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48073. * A PointLight emits the light in every direction.
  48074. * It can cast shadows.
  48075. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48076. * ```javascript
  48077. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48078. * ```
  48079. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48080. * @param name The light friendly name
  48081. * @param position The position of the point light in the scene
  48082. * @param scene The scene the lights belongs to
  48083. */
  48084. function PointLight(name, position, scene) {
  48085. var _this = _super.call(this, name, scene) || this;
  48086. _this._shadowAngle = Math.PI / 2;
  48087. _this.position = position;
  48088. return _this;
  48089. }
  48090. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48091. /**
  48092. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48093. * This specifies what angle the shadow will use to be created.
  48094. *
  48095. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48096. */
  48097. get: function () {
  48098. return this._shadowAngle;
  48099. },
  48100. /**
  48101. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48102. * This specifies what angle the shadow will use to be created.
  48103. *
  48104. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48105. */
  48106. set: function (value) {
  48107. this._shadowAngle = value;
  48108. this.forceProjectionMatrixCompute();
  48109. },
  48110. enumerable: true,
  48111. configurable: true
  48112. });
  48113. Object.defineProperty(PointLight.prototype, "direction", {
  48114. /**
  48115. * Gets the direction if it has been set.
  48116. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48117. */
  48118. get: function () {
  48119. return this._direction;
  48120. },
  48121. /**
  48122. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48123. */
  48124. set: function (value) {
  48125. var previousNeedCube = this.needCube();
  48126. this._direction = value;
  48127. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48128. this._shadowGenerator.recreateShadowMap();
  48129. }
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. /**
  48135. * Returns the string "PointLight"
  48136. * @returns the class name
  48137. */
  48138. PointLight.prototype.getClassName = function () {
  48139. return "PointLight";
  48140. };
  48141. /**
  48142. * Returns the integer 0.
  48143. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48144. */
  48145. PointLight.prototype.getTypeID = function () {
  48146. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48147. };
  48148. /**
  48149. * Specifies wether or not the shadowmap should be a cube texture.
  48150. * @returns true if the shadowmap needs to be a cube texture.
  48151. */
  48152. PointLight.prototype.needCube = function () {
  48153. return !this.direction;
  48154. };
  48155. /**
  48156. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48157. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48158. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48159. */
  48160. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48161. if (this.direction) {
  48162. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48163. }
  48164. else {
  48165. switch (faceIndex) {
  48166. case 0:
  48167. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48168. case 1:
  48169. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48170. case 2:
  48171. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48172. case 3:
  48173. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48174. case 4:
  48175. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48176. case 5:
  48177. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48178. }
  48179. }
  48180. return BABYLON.Vector3.Zero();
  48181. };
  48182. /**
  48183. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48184. * - fov = PI / 2
  48185. * - aspect ratio : 1.0
  48186. * - z-near and far equal to the active camera minZ and maxZ.
  48187. * Returns the PointLight.
  48188. */
  48189. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48190. var activeCamera = this.getScene().activeCamera;
  48191. if (!activeCamera) {
  48192. return;
  48193. }
  48194. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48195. };
  48196. PointLight.prototype._buildUniformLayout = function () {
  48197. this._uniformBuffer.addUniform("vLightData", 4);
  48198. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48199. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48200. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48201. this._uniformBuffer.addUniform("depthValues", 2);
  48202. this._uniformBuffer.create();
  48203. };
  48204. /**
  48205. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48206. * @param effect The effect to update
  48207. * @param lightIndex The index of the light in the effect to update
  48208. * @returns The point light
  48209. */
  48210. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48211. if (this.computeTransformedInformation()) {
  48212. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48213. return this;
  48214. }
  48215. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48216. return this;
  48217. };
  48218. /**
  48219. * Prepares the list of defines specific to the light type.
  48220. * @param defines the list of defines
  48221. * @param lightIndex defines the index of the light for the effect
  48222. */
  48223. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48224. defines["POINTLIGHT" + lightIndex] = true;
  48225. };
  48226. __decorate([
  48227. BABYLON.serialize()
  48228. ], PointLight.prototype, "shadowAngle", null);
  48229. return PointLight;
  48230. }(BABYLON.ShadowLight));
  48231. BABYLON.PointLight = PointLight;
  48232. })(BABYLON || (BABYLON = {}));
  48233. //# sourceMappingURL=babylon.pointLight.js.map
  48234. var BABYLON;
  48235. (function (BABYLON) {
  48236. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48237. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48238. });
  48239. /**
  48240. * A directional light is defined by a direction (what a surprise!).
  48241. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48242. * 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.
  48243. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48244. */
  48245. var DirectionalLight = /** @class */ (function (_super) {
  48246. __extends(DirectionalLight, _super);
  48247. /**
  48248. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48249. * The directional light is emitted from everywhere in the given direction.
  48250. * It can cast shawdows.
  48251. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48252. * @param name The friendly name of the light
  48253. * @param direction The direction of the light
  48254. * @param scene The scene the light belongs to
  48255. */
  48256. function DirectionalLight(name, direction, scene) {
  48257. var _this = _super.call(this, name, scene) || this;
  48258. _this._shadowFrustumSize = 0;
  48259. _this._shadowOrthoScale = 0.1;
  48260. /**
  48261. * Automatically compute the projection matrix to best fit (including all the casters)
  48262. * on each frame.
  48263. */
  48264. _this.autoUpdateExtends = true;
  48265. // Cache
  48266. _this._orthoLeft = Number.MAX_VALUE;
  48267. _this._orthoRight = Number.MIN_VALUE;
  48268. _this._orthoTop = Number.MIN_VALUE;
  48269. _this._orthoBottom = Number.MAX_VALUE;
  48270. _this.position = direction.scale(-1.0);
  48271. _this.direction = direction;
  48272. return _this;
  48273. }
  48274. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48275. /**
  48276. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48277. */
  48278. get: function () {
  48279. return this._shadowFrustumSize;
  48280. },
  48281. /**
  48282. * Specifies a fix frustum size for the shadow generation.
  48283. */
  48284. set: function (value) {
  48285. this._shadowFrustumSize = value;
  48286. this.forceProjectionMatrixCompute();
  48287. },
  48288. enumerable: true,
  48289. configurable: true
  48290. });
  48291. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48292. /**
  48293. * Gets the shadow projection scale against the optimal computed one.
  48294. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48295. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48296. */
  48297. get: function () {
  48298. return this._shadowOrthoScale;
  48299. },
  48300. /**
  48301. * Sets the shadow projection scale against the optimal computed one.
  48302. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48303. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48304. */
  48305. set: function (value) {
  48306. this._shadowOrthoScale = value;
  48307. this.forceProjectionMatrixCompute();
  48308. },
  48309. enumerable: true,
  48310. configurable: true
  48311. });
  48312. /**
  48313. * Returns the string "DirectionalLight".
  48314. * @return The class name
  48315. */
  48316. DirectionalLight.prototype.getClassName = function () {
  48317. return "DirectionalLight";
  48318. };
  48319. /**
  48320. * Returns the integer 1.
  48321. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48322. */
  48323. DirectionalLight.prototype.getTypeID = function () {
  48324. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48325. };
  48326. /**
  48327. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48328. * Returns the DirectionalLight Shadow projection matrix.
  48329. */
  48330. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48331. if (this.shadowFrustumSize > 0) {
  48332. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48333. }
  48334. else {
  48335. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48336. }
  48337. };
  48338. /**
  48339. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48340. * Returns the DirectionalLight Shadow projection matrix.
  48341. */
  48342. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48343. var activeCamera = this.getScene().activeCamera;
  48344. if (!activeCamera) {
  48345. return;
  48346. }
  48347. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48348. };
  48349. /**
  48350. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48351. * Returns the DirectionalLight Shadow projection matrix.
  48352. */
  48353. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48354. var activeCamera = this.getScene().activeCamera;
  48355. if (!activeCamera) {
  48356. return;
  48357. }
  48358. // Check extends
  48359. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48360. var tempVector3 = BABYLON.Vector3.Zero();
  48361. this._orthoLeft = Number.MAX_VALUE;
  48362. this._orthoRight = Number.MIN_VALUE;
  48363. this._orthoTop = Number.MIN_VALUE;
  48364. this._orthoBottom = Number.MAX_VALUE;
  48365. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48366. var mesh = renderList[meshIndex];
  48367. if (!mesh) {
  48368. continue;
  48369. }
  48370. var boundingInfo = mesh.getBoundingInfo();
  48371. var boundingBox = boundingInfo.boundingBox;
  48372. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48373. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48374. if (tempVector3.x < this._orthoLeft)
  48375. this._orthoLeft = tempVector3.x;
  48376. if (tempVector3.y < this._orthoBottom)
  48377. this._orthoBottom = tempVector3.y;
  48378. if (tempVector3.x > this._orthoRight)
  48379. this._orthoRight = tempVector3.x;
  48380. if (tempVector3.y > this._orthoTop)
  48381. this._orthoTop = tempVector3.y;
  48382. }
  48383. }
  48384. }
  48385. var xOffset = this._orthoRight - this._orthoLeft;
  48386. var yOffset = this._orthoTop - this._orthoBottom;
  48387. 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);
  48388. };
  48389. DirectionalLight.prototype._buildUniformLayout = function () {
  48390. this._uniformBuffer.addUniform("vLightData", 4);
  48391. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48392. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48393. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48394. this._uniformBuffer.addUniform("depthValues", 2);
  48395. this._uniformBuffer.create();
  48396. };
  48397. /**
  48398. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48399. * @param effect The effect to update
  48400. * @param lightIndex The index of the light in the effect to update
  48401. * @returns The directional light
  48402. */
  48403. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48404. if (this.computeTransformedInformation()) {
  48405. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48406. return this;
  48407. }
  48408. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48409. return this;
  48410. };
  48411. /**
  48412. * Gets the minZ used for shadow according to both the scene and the light.
  48413. *
  48414. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48415. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48416. * @param activeCamera The camera we are returning the min for
  48417. * @returns the depth min z
  48418. */
  48419. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48420. return 1;
  48421. };
  48422. /**
  48423. * Gets the maxZ used for shadow according to both the scene and the light.
  48424. *
  48425. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48426. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48427. * @param activeCamera The camera we are returning the max for
  48428. * @returns the depth max z
  48429. */
  48430. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48431. return 1;
  48432. };
  48433. /**
  48434. * Prepares the list of defines specific to the light type.
  48435. * @param defines the list of defines
  48436. * @param lightIndex defines the index of the light for the effect
  48437. */
  48438. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48439. defines["DIRLIGHT" + lightIndex] = true;
  48440. };
  48441. __decorate([
  48442. BABYLON.serialize()
  48443. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48444. __decorate([
  48445. BABYLON.serialize()
  48446. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48447. __decorate([
  48448. BABYLON.serialize()
  48449. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48450. return DirectionalLight;
  48451. }(BABYLON.ShadowLight));
  48452. BABYLON.DirectionalLight = DirectionalLight;
  48453. })(BABYLON || (BABYLON = {}));
  48454. //# sourceMappingURL=babylon.directionalLight.js.map
  48455. var BABYLON;
  48456. (function (BABYLON) {
  48457. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48458. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48459. });
  48460. /**
  48461. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48462. * These values define a cone of light starting from the position, emitting toward the direction.
  48463. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48464. * and the exponent defines the speed of the decay of the light with distance (reach).
  48465. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48466. */
  48467. var SpotLight = /** @class */ (function (_super) {
  48468. __extends(SpotLight, _super);
  48469. /**
  48470. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48471. * It can cast shadows.
  48472. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48473. * @param name The light friendly name
  48474. * @param position The position of the spot light in the scene
  48475. * @param direction The direction of the light in the scene
  48476. * @param angle The cone angle of the light in Radians
  48477. * @param exponent The light decay speed with the distance from the emission spot
  48478. * @param scene The scene the lights belongs to
  48479. */
  48480. function SpotLight(name, position, direction, angle, exponent, scene) {
  48481. var _this = _super.call(this, name, scene) || this;
  48482. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48483. _this._projectionTextureLightNear = 1e-6;
  48484. _this._projectionTextureLightFar = 1000.0;
  48485. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48486. _this._projectionTextureViewLightDirty = true;
  48487. _this._projectionTextureProjectionLightDirty = true;
  48488. _this._projectionTextureDirty = true;
  48489. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48490. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48491. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48492. _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);
  48493. _this.position = position;
  48494. _this.direction = direction;
  48495. _this.angle = angle;
  48496. _this.exponent = exponent;
  48497. return _this;
  48498. }
  48499. Object.defineProperty(SpotLight.prototype, "angle", {
  48500. /**
  48501. * Gets the cone angle of the spot light in Radians.
  48502. */
  48503. get: function () {
  48504. return this._angle;
  48505. },
  48506. /**
  48507. * Sets the cone angle of the spot light in Radians.
  48508. */
  48509. set: function (value) {
  48510. this._angle = value;
  48511. this._projectionTextureProjectionLightDirty = true;
  48512. this.forceProjectionMatrixCompute();
  48513. },
  48514. enumerable: true,
  48515. configurable: true
  48516. });
  48517. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48518. /**
  48519. * Allows scaling the angle of the light for shadow generation only.
  48520. */
  48521. get: function () {
  48522. return this._shadowAngleScale;
  48523. },
  48524. /**
  48525. * Allows scaling the angle of the light for shadow generation only.
  48526. */
  48527. set: function (value) {
  48528. this._shadowAngleScale = value;
  48529. this.forceProjectionMatrixCompute();
  48530. },
  48531. enumerable: true,
  48532. configurable: true
  48533. });
  48534. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48535. /**
  48536. * Allows reading the projecton texture
  48537. */
  48538. get: function () {
  48539. return this._projectionTextureMatrix;
  48540. },
  48541. enumerable: true,
  48542. configurable: true
  48543. });
  48544. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48545. /**
  48546. * Gets the near clip of the Spotlight for texture projection.
  48547. */
  48548. get: function () {
  48549. return this._projectionTextureLightNear;
  48550. },
  48551. /**
  48552. * Sets the near clip of the Spotlight for texture projection.
  48553. */
  48554. set: function (value) {
  48555. this._projectionTextureLightNear = value;
  48556. this._projectionTextureProjectionLightDirty = true;
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48562. /**
  48563. * Gets the far clip of the Spotlight for texture projection.
  48564. */
  48565. get: function () {
  48566. return this._projectionTextureLightFar;
  48567. },
  48568. /**
  48569. * Sets the far clip of the Spotlight for texture projection.
  48570. */
  48571. set: function (value) {
  48572. this._projectionTextureLightFar = value;
  48573. this._projectionTextureProjectionLightDirty = true;
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48579. /**
  48580. * Gets the Up vector of the Spotlight for texture projection.
  48581. */
  48582. get: function () {
  48583. return this._projectionTextureUpDirection;
  48584. },
  48585. /**
  48586. * Sets the Up vector of the Spotlight for texture projection.
  48587. */
  48588. set: function (value) {
  48589. this._projectionTextureUpDirection = value;
  48590. this._projectionTextureProjectionLightDirty = true;
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48596. /**
  48597. * Gets the projection texture of the light.
  48598. */
  48599. get: function () {
  48600. return this._projectionTexture;
  48601. },
  48602. /**
  48603. * Sets the projection texture of the light.
  48604. */
  48605. set: function (value) {
  48606. this._projectionTexture = value;
  48607. this._projectionTextureDirty = true;
  48608. },
  48609. enumerable: true,
  48610. configurable: true
  48611. });
  48612. /**
  48613. * Returns the string "SpotLight".
  48614. * @returns the class name
  48615. */
  48616. SpotLight.prototype.getClassName = function () {
  48617. return "SpotLight";
  48618. };
  48619. /**
  48620. * Returns the integer 2.
  48621. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48622. */
  48623. SpotLight.prototype.getTypeID = function () {
  48624. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48625. };
  48626. /**
  48627. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48628. */
  48629. SpotLight.prototype._setDirection = function (value) {
  48630. _super.prototype._setDirection.call(this, value);
  48631. this._projectionTextureViewLightDirty = true;
  48632. };
  48633. /**
  48634. * Overrides the position setter to recompute the projection texture view light Matrix.
  48635. */
  48636. SpotLight.prototype._setPosition = function (value) {
  48637. _super.prototype._setPosition.call(this, value);
  48638. this._projectionTextureViewLightDirty = true;
  48639. };
  48640. /**
  48641. * 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.
  48642. * Returns the SpotLight.
  48643. */
  48644. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48645. var activeCamera = this.getScene().activeCamera;
  48646. if (!activeCamera) {
  48647. return;
  48648. }
  48649. this._shadowAngleScale = this._shadowAngleScale || 1;
  48650. var angle = this._shadowAngleScale * this._angle;
  48651. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48652. };
  48653. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48654. this._projectionTextureViewLightDirty = false;
  48655. this._projectionTextureDirty = true;
  48656. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48657. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48658. };
  48659. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48660. this._projectionTextureProjectionLightDirty = false;
  48661. this._projectionTextureDirty = true;
  48662. var light_far = this.projectionTextureLightFar;
  48663. var light_near = this.projectionTextureLightNear;
  48664. var P = light_far / (light_far - light_near);
  48665. var Q = -P * light_near;
  48666. var S = 1.0 / Math.tan(this._angle / 2.0);
  48667. var A = 1.0;
  48668. 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);
  48669. };
  48670. /**
  48671. * Main function for light texture projection matrix computing.
  48672. */
  48673. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48674. this._projectionTextureDirty = false;
  48675. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48676. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48677. };
  48678. SpotLight.prototype._buildUniformLayout = function () {
  48679. this._uniformBuffer.addUniform("vLightData", 4);
  48680. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48681. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48682. this._uniformBuffer.addUniform("vLightDirection", 3);
  48683. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48684. this._uniformBuffer.addUniform("depthValues", 2);
  48685. this._uniformBuffer.create();
  48686. };
  48687. /**
  48688. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48689. * @param effect The effect to update
  48690. * @param lightIndex The index of the light in the effect to update
  48691. * @returns The spot light
  48692. */
  48693. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48694. var normalizeDirection;
  48695. if (this.computeTransformedInformation()) {
  48696. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48697. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48698. }
  48699. else {
  48700. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48701. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48702. }
  48703. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48704. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48705. if (this._projectionTextureViewLightDirty) {
  48706. this._computeProjectionTextureViewLightMatrix();
  48707. }
  48708. if (this._projectionTextureProjectionLightDirty) {
  48709. this._computeProjectionTextureProjectionLightMatrix();
  48710. }
  48711. if (this._projectionTextureDirty) {
  48712. this._computeProjectionTextureMatrix();
  48713. }
  48714. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48715. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48716. }
  48717. return this;
  48718. };
  48719. /**
  48720. * Disposes the light and the associated resources.
  48721. */
  48722. SpotLight.prototype.dispose = function () {
  48723. _super.prototype.dispose.call(this);
  48724. if (this._projectionTexture) {
  48725. this._projectionTexture.dispose();
  48726. }
  48727. };
  48728. /**
  48729. * Prepares the list of defines specific to the light type.
  48730. * @param defines the list of defines
  48731. * @param lightIndex defines the index of the light for the effect
  48732. */
  48733. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48734. defines["SPOTLIGHT" + lightIndex] = true;
  48735. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  48736. };
  48737. __decorate([
  48738. BABYLON.serialize()
  48739. ], SpotLight.prototype, "angle", null);
  48740. __decorate([
  48741. BABYLON.serialize()
  48742. ], SpotLight.prototype, "shadowAngleScale", null);
  48743. __decorate([
  48744. BABYLON.serialize()
  48745. ], SpotLight.prototype, "exponent", void 0);
  48746. __decorate([
  48747. BABYLON.serialize()
  48748. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48749. __decorate([
  48750. BABYLON.serialize()
  48751. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48752. __decorate([
  48753. BABYLON.serialize()
  48754. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48755. __decorate([
  48756. BABYLON.serializeAsTexture("projectedLightTexture")
  48757. ], SpotLight.prototype, "_projectionTexture", void 0);
  48758. return SpotLight;
  48759. }(BABYLON.ShadowLight));
  48760. BABYLON.SpotLight = SpotLight;
  48761. })(BABYLON || (BABYLON = {}));
  48762. //# sourceMappingURL=babylon.spotLight.js.map
  48763. var BABYLON;
  48764. (function (BABYLON) {
  48765. /**
  48766. * Class used to override all child animations of a given target
  48767. */
  48768. var AnimationPropertiesOverride = /** @class */ (function () {
  48769. function AnimationPropertiesOverride() {
  48770. /**
  48771. * Gets or sets a value indicating if animation blending must be used
  48772. */
  48773. this.enableBlending = false;
  48774. /**
  48775. * Gets or sets the blending speed to use when enableBlending is true
  48776. */
  48777. this.blendingSpeed = 0.01;
  48778. /**
  48779. * Gets or sets the default loop mode to use
  48780. */
  48781. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48782. }
  48783. return AnimationPropertiesOverride;
  48784. }());
  48785. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48786. })(BABYLON || (BABYLON = {}));
  48787. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48788. var BABYLON;
  48789. (function (BABYLON) {
  48790. /**
  48791. * Represents the range of an animation
  48792. */
  48793. var AnimationRange = /** @class */ (function () {
  48794. /**
  48795. * Initializes the range of an animation
  48796. * @param name The name of the animation range
  48797. * @param from The starting frame of the animation
  48798. * @param to The ending frame of the animation
  48799. */
  48800. function AnimationRange(
  48801. /**The name of the animation range**/
  48802. name,
  48803. /**The starting frame of the animation */
  48804. from,
  48805. /**The ending frame of the animation*/
  48806. to) {
  48807. this.name = name;
  48808. this.from = from;
  48809. this.to = to;
  48810. }
  48811. /**
  48812. * Makes a copy of the animation range
  48813. * @returns A copy of the animation range
  48814. */
  48815. AnimationRange.prototype.clone = function () {
  48816. return new AnimationRange(this.name, this.from, this.to);
  48817. };
  48818. return AnimationRange;
  48819. }());
  48820. BABYLON.AnimationRange = AnimationRange;
  48821. /**
  48822. * Composed of a frame, and an action function
  48823. */
  48824. var AnimationEvent = /** @class */ (function () {
  48825. /**
  48826. * Initializes the animation event
  48827. * @param frame The frame for which the event is triggered
  48828. * @param action The event to perform when triggered
  48829. * @param onlyOnce Specifies if the event should be triggered only once
  48830. */
  48831. function AnimationEvent(
  48832. /** The frame for which the event is triggered **/
  48833. frame,
  48834. /** The event to perform when triggered **/
  48835. action,
  48836. /** Specifies if the event should be triggered only once**/
  48837. onlyOnce) {
  48838. this.frame = frame;
  48839. this.action = action;
  48840. this.onlyOnce = onlyOnce;
  48841. /**
  48842. * Specifies if the animation event is done
  48843. */
  48844. this.isDone = false;
  48845. }
  48846. /** @hidden */
  48847. AnimationEvent.prototype._clone = function () {
  48848. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  48849. };
  48850. return AnimationEvent;
  48851. }());
  48852. BABYLON.AnimationEvent = AnimationEvent;
  48853. /**
  48854. * A cursor which tracks a point on a path
  48855. */
  48856. var PathCursor = /** @class */ (function () {
  48857. /**
  48858. * Initializes the path cursor
  48859. * @param path The path to track
  48860. */
  48861. function PathCursor(path) {
  48862. this.path = path;
  48863. /**
  48864. * Stores path cursor callbacks for when an onchange event is triggered
  48865. */
  48866. this._onchange = new Array();
  48867. /**
  48868. * The value of the path cursor
  48869. */
  48870. this.value = 0;
  48871. /**
  48872. * The animation array of the path cursor
  48873. */
  48874. this.animations = new Array();
  48875. }
  48876. /**
  48877. * Gets the cursor point on the path
  48878. * @returns A point on the path cursor at the cursor location
  48879. */
  48880. PathCursor.prototype.getPoint = function () {
  48881. var point = this.path.getPointAtLengthPosition(this.value);
  48882. return new BABYLON.Vector3(point.x, 0, point.y);
  48883. };
  48884. /**
  48885. * Moves the cursor ahead by the step amount
  48886. * @param step The amount to move the cursor forward
  48887. * @returns This path cursor
  48888. */
  48889. PathCursor.prototype.moveAhead = function (step) {
  48890. if (step === void 0) { step = 0.002; }
  48891. this.move(step);
  48892. return this;
  48893. };
  48894. /**
  48895. * Moves the cursor behind by the step amount
  48896. * @param step The amount to move the cursor back
  48897. * @returns This path cursor
  48898. */
  48899. PathCursor.prototype.moveBack = function (step) {
  48900. if (step === void 0) { step = 0.002; }
  48901. this.move(-step);
  48902. return this;
  48903. };
  48904. /**
  48905. * Moves the cursor by the step amount
  48906. * If the step amount is greater than one, an exception is thrown
  48907. * @param step The amount to move the cursor
  48908. * @returns This path cursor
  48909. */
  48910. PathCursor.prototype.move = function (step) {
  48911. if (Math.abs(step) > 1) {
  48912. throw "step size should be less than 1.";
  48913. }
  48914. this.value += step;
  48915. this.ensureLimits();
  48916. this.raiseOnChange();
  48917. return this;
  48918. };
  48919. /**
  48920. * Ensures that the value is limited between zero and one
  48921. * @returns This path cursor
  48922. */
  48923. PathCursor.prototype.ensureLimits = function () {
  48924. while (this.value > 1) {
  48925. this.value -= 1;
  48926. }
  48927. while (this.value < 0) {
  48928. this.value += 1;
  48929. }
  48930. return this;
  48931. };
  48932. /**
  48933. * Runs onchange callbacks on change (used by the animation engine)
  48934. * @returns This path cursor
  48935. */
  48936. PathCursor.prototype.raiseOnChange = function () {
  48937. var _this = this;
  48938. this._onchange.forEach(function (f) { return f(_this); });
  48939. return this;
  48940. };
  48941. /**
  48942. * Executes a function on change
  48943. * @param f A path cursor onchange callback
  48944. * @returns This path cursor
  48945. */
  48946. PathCursor.prototype.onchange = function (f) {
  48947. this._onchange.push(f);
  48948. return this;
  48949. };
  48950. return PathCursor;
  48951. }());
  48952. BABYLON.PathCursor = PathCursor;
  48953. /**
  48954. * Enum for the animation key frame interpolation type
  48955. */
  48956. var AnimationKeyInterpolation;
  48957. (function (AnimationKeyInterpolation) {
  48958. /**
  48959. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  48960. */
  48961. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  48962. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  48963. /**
  48964. * Class used to store any kind of animation
  48965. */
  48966. var Animation = /** @class */ (function () {
  48967. /**
  48968. * Initializes the animation
  48969. * @param name Name of the animation
  48970. * @param targetProperty Property to animate
  48971. * @param framePerSecond The frames per second of the animation
  48972. * @param dataType The data type of the animation
  48973. * @param loopMode The loop mode of the animation
  48974. * @param enableBlendings Specifies if blending should be enabled
  48975. */
  48976. function Animation(
  48977. /**Name of the animation */
  48978. name,
  48979. /**Property to animate */
  48980. targetProperty,
  48981. /**The frames per second of the animation */
  48982. framePerSecond,
  48983. /**The data type of the animation */
  48984. dataType,
  48985. /**The loop mode of the animation */
  48986. loopMode,
  48987. /**Specifies if blending should be enabled */
  48988. enableBlending) {
  48989. this.name = name;
  48990. this.targetProperty = targetProperty;
  48991. this.framePerSecond = framePerSecond;
  48992. this.dataType = dataType;
  48993. this.loopMode = loopMode;
  48994. this.enableBlending = enableBlending;
  48995. /**
  48996. * @hidden Internal use only
  48997. */
  48998. this._runtimeAnimations = new Array();
  48999. /**
  49000. * The set of event that will be linked to this animation
  49001. */
  49002. this._events = new Array();
  49003. /**
  49004. * Stores the blending speed of the animation
  49005. */
  49006. this.blendingSpeed = 0.01;
  49007. /**
  49008. * Stores the animation ranges for the animation
  49009. */
  49010. this._ranges = {};
  49011. this.targetPropertyPath = targetProperty.split(".");
  49012. this.dataType = dataType;
  49013. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49014. }
  49015. /**
  49016. * @hidden Internal use
  49017. */
  49018. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49019. var dataType = undefined;
  49020. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49021. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49022. }
  49023. else if (from instanceof BABYLON.Quaternion) {
  49024. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49025. }
  49026. else if (from instanceof BABYLON.Vector3) {
  49027. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49028. }
  49029. else if (from instanceof BABYLON.Vector2) {
  49030. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49031. }
  49032. else if (from instanceof BABYLON.Color3) {
  49033. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49034. }
  49035. else if (from instanceof BABYLON.Size) {
  49036. dataType = Animation.ANIMATIONTYPE_SIZE;
  49037. }
  49038. if (dataType == undefined) {
  49039. return null;
  49040. }
  49041. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49042. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49043. animation.setKeys(keys);
  49044. if (easingFunction !== undefined) {
  49045. animation.setEasingFunction(easingFunction);
  49046. }
  49047. return animation;
  49048. };
  49049. /**
  49050. * Sets up an animation
  49051. * @param property The property to animate
  49052. * @param animationType The animation type to apply
  49053. * @param framePerSecond The frames per second of the animation
  49054. * @param easingFunction The easing function used in the animation
  49055. * @returns The created animation
  49056. */
  49057. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49058. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49059. animation.setEasingFunction(easingFunction);
  49060. return animation;
  49061. };
  49062. /**
  49063. * Create and start an animation on a node
  49064. * @param name defines the name of the global animation that will be run on all nodes
  49065. * @param node defines the root node where the animation will take place
  49066. * @param targetProperty defines property to animate
  49067. * @param framePerSecond defines the number of frame per second yo use
  49068. * @param totalFrame defines the number of frames in total
  49069. * @param from defines the initial value
  49070. * @param to defines the final value
  49071. * @param loopMode defines which loop mode you want to use (off by default)
  49072. * @param easingFunction defines the easing function to use (linear by default)
  49073. * @param onAnimationEnd defines the callback to call when animation end
  49074. * @returns the animatable created for this animation
  49075. */
  49076. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49078. if (!animation) {
  49079. return null;
  49080. }
  49081. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49082. };
  49083. /**
  49084. * Create and start an animation on a node and its descendants
  49085. * @param name defines the name of the global animation that will be run on all nodes
  49086. * @param node defines the root node where the animation will take place
  49087. * @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
  49088. * @param targetProperty defines property to animate
  49089. * @param framePerSecond defines the number of frame per second to use
  49090. * @param totalFrame defines the number of frames in total
  49091. * @param from defines the initial value
  49092. * @param to defines the final value
  49093. * @param loopMode defines which loop mode you want to use (off by default)
  49094. * @param easingFunction defines the easing function to use (linear by default)
  49095. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49096. * @returns the list of animatables created for all nodes
  49097. * @example https://www.babylonjs-playground.com/#MH0VLI
  49098. */
  49099. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49100. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49101. if (!animation) {
  49102. return null;
  49103. }
  49104. var scene = node.getScene();
  49105. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49106. };
  49107. /**
  49108. * Creates a new animation, merges it with the existing animations and starts it
  49109. * @param name Name of the animation
  49110. * @param node Node which contains the scene that begins the animations
  49111. * @param targetProperty Specifies which property to animate
  49112. * @param framePerSecond The frames per second of the animation
  49113. * @param totalFrame The total number of frames
  49114. * @param from The frame at the beginning of the animation
  49115. * @param to The frame at the end of the animation
  49116. * @param loopMode Specifies the loop mode of the animation
  49117. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49118. * @param onAnimationEnd Callback to run once the animation is complete
  49119. * @returns Nullable animation
  49120. */
  49121. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49122. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49123. if (!animation) {
  49124. return null;
  49125. }
  49126. node.animations.push(animation);
  49127. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49128. };
  49129. /**
  49130. * Transition property of an host to the target Value
  49131. * @param property The property to transition
  49132. * @param targetValue The target Value of the property
  49133. * @param host The object where the property to animate belongs
  49134. * @param scene Scene used to run the animation
  49135. * @param frameRate Framerate (in frame/s) to use
  49136. * @param transition The transition type we want to use
  49137. * @param duration The duration of the animation, in milliseconds
  49138. * @param onAnimationEnd Callback trigger at the end of the animation
  49139. * @returns Nullable animation
  49140. */
  49141. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49142. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49143. if (duration <= 0) {
  49144. host[property] = targetValue;
  49145. if (onAnimationEnd) {
  49146. onAnimationEnd();
  49147. }
  49148. return null;
  49149. }
  49150. var endFrame = frameRate * (duration / 1000);
  49151. transition.setKeys([{
  49152. frame: 0,
  49153. value: host[property].clone ? host[property].clone() : host[property]
  49154. },
  49155. {
  49156. frame: endFrame,
  49157. value: targetValue
  49158. }]);
  49159. if (!host.animations) {
  49160. host.animations = [];
  49161. }
  49162. host.animations.push(transition);
  49163. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49164. animation.onAnimationEnd = onAnimationEnd;
  49165. return animation;
  49166. };
  49167. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49168. /**
  49169. * Return the array of runtime animations currently using this animation
  49170. */
  49171. get: function () {
  49172. return this._runtimeAnimations;
  49173. },
  49174. enumerable: true,
  49175. configurable: true
  49176. });
  49177. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49178. /**
  49179. * Specifies if any of the runtime animations are currently running
  49180. */
  49181. get: function () {
  49182. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49183. var runtimeAnimation = _a[_i];
  49184. if (!runtimeAnimation.isStopped) {
  49185. return true;
  49186. }
  49187. }
  49188. return false;
  49189. },
  49190. enumerable: true,
  49191. configurable: true
  49192. });
  49193. // Methods
  49194. /**
  49195. * Converts the animation to a string
  49196. * @param fullDetails support for multiple levels of logging within scene loading
  49197. * @returns String form of the animation
  49198. */
  49199. Animation.prototype.toString = function (fullDetails) {
  49200. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49201. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49202. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49203. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49204. if (fullDetails) {
  49205. ret += ", Ranges: {";
  49206. var first = true;
  49207. for (var name in this._ranges) {
  49208. if (first) {
  49209. ret += ", ";
  49210. first = false;
  49211. }
  49212. ret += name;
  49213. }
  49214. ret += "}";
  49215. }
  49216. return ret;
  49217. };
  49218. /**
  49219. * Add an event to this animation
  49220. * @param event Event to add
  49221. */
  49222. Animation.prototype.addEvent = function (event) {
  49223. this._events.push(event);
  49224. };
  49225. /**
  49226. * Remove all events found at the given frame
  49227. * @param frame The frame to remove events from
  49228. */
  49229. Animation.prototype.removeEvents = function (frame) {
  49230. for (var index = 0; index < this._events.length; index++) {
  49231. if (this._events[index].frame === frame) {
  49232. this._events.splice(index, 1);
  49233. index--;
  49234. }
  49235. }
  49236. };
  49237. /**
  49238. * Retrieves all the events from the animation
  49239. * @returns Events from the animation
  49240. */
  49241. Animation.prototype.getEvents = function () {
  49242. return this._events;
  49243. };
  49244. /**
  49245. * Creates an animation range
  49246. * @param name Name of the animation range
  49247. * @param from Starting frame of the animation range
  49248. * @param to Ending frame of the animation
  49249. */
  49250. Animation.prototype.createRange = function (name, from, to) {
  49251. // check name not already in use; could happen for bones after serialized
  49252. if (!this._ranges[name]) {
  49253. this._ranges[name] = new AnimationRange(name, from, to);
  49254. }
  49255. };
  49256. /**
  49257. * Deletes an animation range by name
  49258. * @param name Name of the animation range to delete
  49259. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49260. */
  49261. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49262. if (deleteFrames === void 0) { deleteFrames = true; }
  49263. var range = this._ranges[name];
  49264. if (!range) {
  49265. return;
  49266. }
  49267. if (deleteFrames) {
  49268. var from = range.from;
  49269. var to = range.to;
  49270. // this loop MUST go high to low for multiple splices to work
  49271. for (var key = this._keys.length - 1; key >= 0; key--) {
  49272. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49273. this._keys.splice(key, 1);
  49274. }
  49275. }
  49276. }
  49277. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49278. };
  49279. /**
  49280. * Gets the animation range by name, or null if not defined
  49281. * @param name Name of the animation range
  49282. * @returns Nullable animation range
  49283. */
  49284. Animation.prototype.getRange = function (name) {
  49285. return this._ranges[name];
  49286. };
  49287. /**
  49288. * Gets the key frames from the animation
  49289. * @returns The key frames of the animation
  49290. */
  49291. Animation.prototype.getKeys = function () {
  49292. return this._keys;
  49293. };
  49294. /**
  49295. * Gets the highest frame rate of the animation
  49296. * @returns Highest frame rate of the animation
  49297. */
  49298. Animation.prototype.getHighestFrame = function () {
  49299. var ret = 0;
  49300. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49301. if (ret < this._keys[key].frame) {
  49302. ret = this._keys[key].frame;
  49303. }
  49304. }
  49305. return ret;
  49306. };
  49307. /**
  49308. * Gets the easing function of the animation
  49309. * @returns Easing function of the animation
  49310. */
  49311. Animation.prototype.getEasingFunction = function () {
  49312. return this._easingFunction;
  49313. };
  49314. /**
  49315. * Sets the easing function of the animation
  49316. * @param easingFunction A custom mathematical formula for animation
  49317. */
  49318. Animation.prototype.setEasingFunction = function (easingFunction) {
  49319. this._easingFunction = easingFunction;
  49320. };
  49321. /**
  49322. * Interpolates a scalar linearly
  49323. * @param startValue Start value of the animation curve
  49324. * @param endValue End value of the animation curve
  49325. * @param gradient Scalar amount to interpolate
  49326. * @returns Interpolated scalar value
  49327. */
  49328. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49329. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49330. };
  49331. /**
  49332. * Interpolates a scalar cubically
  49333. * @param startValue Start value of the animation curve
  49334. * @param outTangent End tangent of the animation
  49335. * @param endValue End value of the animation curve
  49336. * @param inTangent Start tangent of the animation curve
  49337. * @param gradient Scalar amount to interpolate
  49338. * @returns Interpolated scalar value
  49339. */
  49340. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49341. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49342. };
  49343. /**
  49344. * Interpolates a quaternion using a spherical linear interpolation
  49345. * @param startValue Start value of the animation curve
  49346. * @param endValue End value of the animation curve
  49347. * @param gradient Scalar amount to interpolate
  49348. * @returns Interpolated quaternion value
  49349. */
  49350. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49351. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49352. };
  49353. /**
  49354. * Interpolates a quaternion cubically
  49355. * @param startValue Start value of the animation curve
  49356. * @param outTangent End tangent of the animation curve
  49357. * @param endValue End value of the animation curve
  49358. * @param inTangent Start tangent of the animation curve
  49359. * @param gradient Scalar amount to interpolate
  49360. * @returns Interpolated quaternion value
  49361. */
  49362. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49363. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49364. };
  49365. /**
  49366. * Interpolates a Vector3 linearl
  49367. * @param startValue Start value of the animation curve
  49368. * @param endValue End value of the animation curve
  49369. * @param gradient Scalar amount to interpolate
  49370. * @returns Interpolated scalar value
  49371. */
  49372. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49373. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49374. };
  49375. /**
  49376. * Interpolates a Vector3 cubically
  49377. * @param startValue Start value of the animation curve
  49378. * @param outTangent End tangent of the animation
  49379. * @param endValue End value of the animation curve
  49380. * @param inTangent Start tangent of the animation curve
  49381. * @param gradient Scalar amount to interpolate
  49382. * @returns InterpolatedVector3 value
  49383. */
  49384. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49385. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49386. };
  49387. /**
  49388. * Interpolates a Vector2 linearly
  49389. * @param startValue Start value of the animation curve
  49390. * @param endValue End value of the animation curve
  49391. * @param gradient Scalar amount to interpolate
  49392. * @returns Interpolated Vector2 value
  49393. */
  49394. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49395. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49396. };
  49397. /**
  49398. * Interpolates a Vector2 cubically
  49399. * @param startValue Start value of the animation curve
  49400. * @param outTangent End tangent of the animation
  49401. * @param endValue End value of the animation curve
  49402. * @param inTangent Start tangent of the animation curve
  49403. * @param gradient Scalar amount to interpolate
  49404. * @returns Interpolated Vector2 value
  49405. */
  49406. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49407. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49408. };
  49409. /**
  49410. * Interpolates a size linearly
  49411. * @param startValue Start value of the animation curve
  49412. * @param endValue End value of the animation curve
  49413. * @param gradient Scalar amount to interpolate
  49414. * @returns Interpolated Size value
  49415. */
  49416. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49417. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49418. };
  49419. /**
  49420. * Interpolates a Color3 linearly
  49421. * @param startValue Start value of the animation curve
  49422. * @param endValue End value of the animation curve
  49423. * @param gradient Scalar amount to interpolate
  49424. * @returns Interpolated Color3 value
  49425. */
  49426. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49427. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49428. };
  49429. /**
  49430. * @hidden Internal use only
  49431. */
  49432. Animation.prototype._getKeyValue = function (value) {
  49433. if (typeof value === "function") {
  49434. return value();
  49435. }
  49436. return value;
  49437. };
  49438. /**
  49439. * @hidden Internal use only
  49440. */
  49441. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49442. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49443. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49444. }
  49445. var keys = this.getKeys();
  49446. // Try to get a hash to find the right key
  49447. 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));
  49448. if (keys[startKeyIndex].frame >= currentFrame) {
  49449. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49450. startKeyIndex--;
  49451. }
  49452. }
  49453. for (var key = startKeyIndex; key < keys.length; key++) {
  49454. var endKey = keys[key + 1];
  49455. if (endKey.frame >= currentFrame) {
  49456. var startKey = keys[key];
  49457. var startValue = this._getKeyValue(startKey.value);
  49458. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49459. return startValue;
  49460. }
  49461. var endValue = this._getKeyValue(endKey.value);
  49462. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49463. var frameDelta = endKey.frame - startKey.frame;
  49464. // gradient : percent of currentFrame between the frame inf and the frame sup
  49465. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49466. // check for easingFunction and correction of gradient
  49467. var easingFunction = this.getEasingFunction();
  49468. if (easingFunction != null) {
  49469. gradient = easingFunction.ease(gradient);
  49470. }
  49471. switch (this.dataType) {
  49472. // Float
  49473. case Animation.ANIMATIONTYPE_FLOAT:
  49474. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49475. switch (loopMode) {
  49476. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49477. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49478. return floatValue;
  49479. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49480. return offsetValue * repeatCount + floatValue;
  49481. }
  49482. break;
  49483. // Quaternion
  49484. case Animation.ANIMATIONTYPE_QUATERNION:
  49485. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49486. switch (loopMode) {
  49487. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49488. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49489. return quatValue;
  49490. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49491. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49492. }
  49493. return quatValue;
  49494. // Vector3
  49495. case Animation.ANIMATIONTYPE_VECTOR3:
  49496. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49497. switch (loopMode) {
  49498. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49499. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49500. return vec3Value;
  49501. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49502. return vec3Value.add(offsetValue.scale(repeatCount));
  49503. }
  49504. // Vector2
  49505. case Animation.ANIMATIONTYPE_VECTOR2:
  49506. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49507. switch (loopMode) {
  49508. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49509. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49510. return vec2Value;
  49511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49512. return vec2Value.add(offsetValue.scale(repeatCount));
  49513. }
  49514. // Size
  49515. case Animation.ANIMATIONTYPE_SIZE:
  49516. switch (loopMode) {
  49517. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49518. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49519. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49520. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49521. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49522. }
  49523. // Color3
  49524. case Animation.ANIMATIONTYPE_COLOR3:
  49525. switch (loopMode) {
  49526. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49527. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49528. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49529. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49530. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49531. }
  49532. // Matrix
  49533. case Animation.ANIMATIONTYPE_MATRIX:
  49534. switch (loopMode) {
  49535. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49536. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49537. if (Animation.AllowMatricesInterpolation) {
  49538. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49539. }
  49540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49541. return startValue;
  49542. }
  49543. default:
  49544. break;
  49545. }
  49546. break;
  49547. }
  49548. }
  49549. return this._getKeyValue(keys[keys.length - 1].value);
  49550. };
  49551. /**
  49552. * Defines the function to use to interpolate matrices
  49553. * @param startValue defines the start matrix
  49554. * @param endValue defines the end matrix
  49555. * @param gradient defines the gradient between both matrices
  49556. * @param result defines an optional target matrix where to store the interpolation
  49557. * @returns the interpolated matrix
  49558. */
  49559. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49560. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49561. if (result) {
  49562. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49563. return result;
  49564. }
  49565. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49566. }
  49567. if (result) {
  49568. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49569. return result;
  49570. }
  49571. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49572. };
  49573. /**
  49574. * Makes a copy of the animation
  49575. * @returns Cloned animation
  49576. */
  49577. Animation.prototype.clone = function () {
  49578. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49579. clone.enableBlending = this.enableBlending;
  49580. clone.blendingSpeed = this.blendingSpeed;
  49581. if (this._keys) {
  49582. clone.setKeys(this._keys);
  49583. }
  49584. if (this._ranges) {
  49585. clone._ranges = {};
  49586. for (var name in this._ranges) {
  49587. var range = this._ranges[name];
  49588. if (!range) {
  49589. continue;
  49590. }
  49591. clone._ranges[name] = range.clone();
  49592. }
  49593. }
  49594. return clone;
  49595. };
  49596. /**
  49597. * Sets the key frames of the animation
  49598. * @param values The animation key frames to set
  49599. */
  49600. Animation.prototype.setKeys = function (values) {
  49601. this._keys = values.slice(0);
  49602. };
  49603. /**
  49604. * Serializes the animation to an object
  49605. * @returns Serialized object
  49606. */
  49607. Animation.prototype.serialize = function () {
  49608. var serializationObject = {};
  49609. serializationObject.name = this.name;
  49610. serializationObject.property = this.targetProperty;
  49611. serializationObject.framePerSecond = this.framePerSecond;
  49612. serializationObject.dataType = this.dataType;
  49613. serializationObject.loopBehavior = this.loopMode;
  49614. serializationObject.enableBlending = this.enableBlending;
  49615. serializationObject.blendingSpeed = this.blendingSpeed;
  49616. var dataType = this.dataType;
  49617. serializationObject.keys = [];
  49618. var keys = this.getKeys();
  49619. for (var index = 0; index < keys.length; index++) {
  49620. var animationKey = keys[index];
  49621. var key = {};
  49622. key.frame = animationKey.frame;
  49623. switch (dataType) {
  49624. case Animation.ANIMATIONTYPE_FLOAT:
  49625. key.values = [animationKey.value];
  49626. break;
  49627. case Animation.ANIMATIONTYPE_QUATERNION:
  49628. case Animation.ANIMATIONTYPE_MATRIX:
  49629. case Animation.ANIMATIONTYPE_VECTOR3:
  49630. case Animation.ANIMATIONTYPE_COLOR3:
  49631. key.values = animationKey.value.asArray();
  49632. break;
  49633. }
  49634. serializationObject.keys.push(key);
  49635. }
  49636. serializationObject.ranges = [];
  49637. for (var name in this._ranges) {
  49638. var source = this._ranges[name];
  49639. if (!source) {
  49640. continue;
  49641. }
  49642. var range = {};
  49643. range.name = name;
  49644. range.from = source.from;
  49645. range.to = source.to;
  49646. serializationObject.ranges.push(range);
  49647. }
  49648. return serializationObject;
  49649. };
  49650. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49651. /**
  49652. * Get the float animation type
  49653. */
  49654. get: function () {
  49655. return Animation._ANIMATIONTYPE_FLOAT;
  49656. },
  49657. enumerable: true,
  49658. configurable: true
  49659. });
  49660. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49661. /**
  49662. * Get the Vector3 animation type
  49663. */
  49664. get: function () {
  49665. return Animation._ANIMATIONTYPE_VECTOR3;
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49671. /**
  49672. * Get the Vectpr2 animation type
  49673. */
  49674. get: function () {
  49675. return Animation._ANIMATIONTYPE_VECTOR2;
  49676. },
  49677. enumerable: true,
  49678. configurable: true
  49679. });
  49680. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49681. /**
  49682. * Get the Size animation type
  49683. */
  49684. get: function () {
  49685. return Animation._ANIMATIONTYPE_SIZE;
  49686. },
  49687. enumerable: true,
  49688. configurable: true
  49689. });
  49690. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49691. /**
  49692. * Get the Quaternion animation type
  49693. */
  49694. get: function () {
  49695. return Animation._ANIMATIONTYPE_QUATERNION;
  49696. },
  49697. enumerable: true,
  49698. configurable: true
  49699. });
  49700. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49701. /**
  49702. * Get the Matrix animation type
  49703. */
  49704. get: function () {
  49705. return Animation._ANIMATIONTYPE_MATRIX;
  49706. },
  49707. enumerable: true,
  49708. configurable: true
  49709. });
  49710. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49711. /**
  49712. * Get the Color3 animation type
  49713. */
  49714. get: function () {
  49715. return Animation._ANIMATIONTYPE_COLOR3;
  49716. },
  49717. enumerable: true,
  49718. configurable: true
  49719. });
  49720. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49721. /**
  49722. * Get the Relative Loop Mode
  49723. */
  49724. get: function () {
  49725. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49731. /**
  49732. * Get the Cycle Loop Mode
  49733. */
  49734. get: function () {
  49735. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49736. },
  49737. enumerable: true,
  49738. configurable: true
  49739. });
  49740. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49741. /**
  49742. * Get the Constant Loop Mode
  49743. */
  49744. get: function () {
  49745. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49746. },
  49747. enumerable: true,
  49748. configurable: true
  49749. });
  49750. /** @hidden */
  49751. Animation._UniversalLerp = function (left, right, amount) {
  49752. var constructor = left.constructor;
  49753. if (constructor.Lerp) { // Lerp supported
  49754. return constructor.Lerp(left, right, amount);
  49755. }
  49756. else if (constructor.Slerp) { // Slerp supported
  49757. return constructor.Slerp(left, right, amount);
  49758. }
  49759. else if (left.toFixed) { // Number
  49760. return left * (1.0 - amount) + amount * right;
  49761. }
  49762. else { // Blending not supported
  49763. return right;
  49764. }
  49765. };
  49766. /**
  49767. * Parses an animation object and creates an animation
  49768. * @param parsedAnimation Parsed animation object
  49769. * @returns Animation object
  49770. */
  49771. Animation.Parse = function (parsedAnimation) {
  49772. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49773. var dataType = parsedAnimation.dataType;
  49774. var keys = [];
  49775. var data;
  49776. var index;
  49777. if (parsedAnimation.enableBlending) {
  49778. animation.enableBlending = parsedAnimation.enableBlending;
  49779. }
  49780. if (parsedAnimation.blendingSpeed) {
  49781. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49782. }
  49783. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49784. var key = parsedAnimation.keys[index];
  49785. var inTangent;
  49786. var outTangent;
  49787. switch (dataType) {
  49788. case Animation.ANIMATIONTYPE_FLOAT:
  49789. data = key.values[0];
  49790. if (key.values.length >= 1) {
  49791. inTangent = key.values[1];
  49792. }
  49793. if (key.values.length >= 2) {
  49794. outTangent = key.values[2];
  49795. }
  49796. break;
  49797. case Animation.ANIMATIONTYPE_QUATERNION:
  49798. data = BABYLON.Quaternion.FromArray(key.values);
  49799. if (key.values.length >= 8) {
  49800. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49801. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49802. inTangent = _inTangent;
  49803. }
  49804. }
  49805. if (key.values.length >= 12) {
  49806. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49807. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49808. outTangent = _outTangent;
  49809. }
  49810. }
  49811. break;
  49812. case Animation.ANIMATIONTYPE_MATRIX:
  49813. data = BABYLON.Matrix.FromArray(key.values);
  49814. break;
  49815. case Animation.ANIMATIONTYPE_COLOR3:
  49816. data = BABYLON.Color3.FromArray(key.values);
  49817. break;
  49818. case Animation.ANIMATIONTYPE_VECTOR3:
  49819. default:
  49820. data = BABYLON.Vector3.FromArray(key.values);
  49821. break;
  49822. }
  49823. var keyData = {};
  49824. keyData.frame = key.frame;
  49825. keyData.value = data;
  49826. if (inTangent != undefined) {
  49827. keyData.inTangent = inTangent;
  49828. }
  49829. if (outTangent != undefined) {
  49830. keyData.outTangent = outTangent;
  49831. }
  49832. keys.push(keyData);
  49833. }
  49834. animation.setKeys(keys);
  49835. if (parsedAnimation.ranges) {
  49836. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49837. data = parsedAnimation.ranges[index];
  49838. animation.createRange(data.name, data.from, data.to);
  49839. }
  49840. }
  49841. return animation;
  49842. };
  49843. /**
  49844. * Appends the serialized animations from the source animations
  49845. * @param source Source containing the animations
  49846. * @param destination Target to store the animations
  49847. */
  49848. Animation.AppendSerializedAnimations = function (source, destination) {
  49849. if (source.animations) {
  49850. destination.animations = [];
  49851. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49852. var animation = source.animations[animationIndex];
  49853. destination.animations.push(animation.serialize());
  49854. }
  49855. }
  49856. };
  49857. /**
  49858. * Use matrix interpolation instead of using direct key value when animating matrices
  49859. */
  49860. Animation.AllowMatricesInterpolation = false;
  49861. /**
  49862. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49863. */
  49864. Animation.AllowMatrixDecomposeForInterpolation = true;
  49865. // Statics
  49866. /**
  49867. * Float animation type
  49868. */
  49869. Animation._ANIMATIONTYPE_FLOAT = 0;
  49870. /**
  49871. * Vector3 animation type
  49872. */
  49873. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49874. /**
  49875. * Quaternion animation type
  49876. */
  49877. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49878. /**
  49879. * Matrix animation type
  49880. */
  49881. Animation._ANIMATIONTYPE_MATRIX = 3;
  49882. /**
  49883. * Color3 animation type
  49884. */
  49885. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49886. /**
  49887. * Vector2 animation type
  49888. */
  49889. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49890. /**
  49891. * Size animation type
  49892. */
  49893. Animation._ANIMATIONTYPE_SIZE = 6;
  49894. /**
  49895. * Relative Loop Mode
  49896. */
  49897. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49898. /**
  49899. * Cycle Loop Mode
  49900. */
  49901. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49902. /**
  49903. * Constant Loop Mode
  49904. */
  49905. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49906. return Animation;
  49907. }());
  49908. BABYLON.Animation = Animation;
  49909. })(BABYLON || (BABYLON = {}));
  49910. //# sourceMappingURL=babylon.animation.js.map
  49911. var BABYLON;
  49912. (function (BABYLON) {
  49913. /**
  49914. * This class defines the direct association between an animation and a target
  49915. */
  49916. var TargetedAnimation = /** @class */ (function () {
  49917. function TargetedAnimation() {
  49918. }
  49919. return TargetedAnimation;
  49920. }());
  49921. BABYLON.TargetedAnimation = TargetedAnimation;
  49922. /**
  49923. * Use this class to create coordinated animations on multiple targets
  49924. */
  49925. var AnimationGroup = /** @class */ (function () {
  49926. function AnimationGroup(name, scene) {
  49927. if (scene === void 0) { scene = null; }
  49928. this.name = name;
  49929. this._targetedAnimations = new Array();
  49930. this._animatables = new Array();
  49931. this._from = Number.MAX_VALUE;
  49932. this._to = -Number.MAX_VALUE;
  49933. this._speedRatio = 1;
  49934. this.onAnimationEndObservable = new BABYLON.Observable();
  49935. /**
  49936. * This observable will notify when all animations have ended.
  49937. */
  49938. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  49939. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49940. this._scene.animationGroups.push(this);
  49941. }
  49942. Object.defineProperty(AnimationGroup.prototype, "from", {
  49943. /**
  49944. * Gets the first frame
  49945. */
  49946. get: function () {
  49947. return this._from;
  49948. },
  49949. enumerable: true,
  49950. configurable: true
  49951. });
  49952. Object.defineProperty(AnimationGroup.prototype, "to", {
  49953. /**
  49954. * Gets the last frame
  49955. */
  49956. get: function () {
  49957. return this._to;
  49958. },
  49959. enumerable: true,
  49960. configurable: true
  49961. });
  49962. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49963. /**
  49964. * Define if the animations are started
  49965. */
  49966. get: function () {
  49967. return this._isStarted;
  49968. },
  49969. enumerable: true,
  49970. configurable: true
  49971. });
  49972. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49973. /**
  49974. * Gets or sets the speed ratio to use for all animations
  49975. */
  49976. get: function () {
  49977. return this._speedRatio;
  49978. },
  49979. /**
  49980. * Gets or sets the speed ratio to use for all animations
  49981. */
  49982. set: function (value) {
  49983. if (this._speedRatio === value) {
  49984. return;
  49985. }
  49986. this._speedRatio = value;
  49987. for (var index = 0; index < this._animatables.length; index++) {
  49988. var animatable = this._animatables[index];
  49989. animatable.speedRatio = this._speedRatio;
  49990. }
  49991. },
  49992. enumerable: true,
  49993. configurable: true
  49994. });
  49995. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49996. /**
  49997. * Gets the targeted animations for this animation group
  49998. */
  49999. get: function () {
  50000. return this._targetedAnimations;
  50001. },
  50002. enumerable: true,
  50003. configurable: true
  50004. });
  50005. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50006. /**
  50007. * returning the list of animatables controlled by this animation group.
  50008. */
  50009. get: function () {
  50010. return this._animatables;
  50011. },
  50012. enumerable: true,
  50013. configurable: true
  50014. });
  50015. /**
  50016. * Add an animation (with its target) in the group
  50017. * @param animation defines the animation we want to add
  50018. * @param target defines the target of the animation
  50019. * @returns the {BABYLON.TargetedAnimation} object
  50020. */
  50021. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50022. var targetedAnimation = {
  50023. animation: animation,
  50024. target: target
  50025. };
  50026. var keys = animation.getKeys();
  50027. if (this._from > keys[0].frame) {
  50028. this._from = keys[0].frame;
  50029. }
  50030. if (this._to < keys[keys.length - 1].frame) {
  50031. this._to = keys[keys.length - 1].frame;
  50032. }
  50033. this._targetedAnimations.push(targetedAnimation);
  50034. return targetedAnimation;
  50035. };
  50036. /**
  50037. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50038. * It can add constant keys at begin or end
  50039. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50040. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50041. */
  50042. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50043. if (beginFrame === void 0) { beginFrame = null; }
  50044. if (endFrame === void 0) { endFrame = null; }
  50045. if (beginFrame == null)
  50046. beginFrame = this._from;
  50047. if (endFrame == null)
  50048. endFrame = this._to;
  50049. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50050. var targetedAnimation = this._targetedAnimations[index];
  50051. var keys = targetedAnimation.animation.getKeys();
  50052. var startKey = keys[0];
  50053. var endKey = keys[keys.length - 1];
  50054. if (startKey.frame > beginFrame) {
  50055. var newKey = {
  50056. frame: beginFrame,
  50057. value: startKey.value,
  50058. inTangent: startKey.inTangent,
  50059. outTangent: startKey.outTangent,
  50060. interpolation: startKey.interpolation
  50061. };
  50062. keys.splice(0, 0, newKey);
  50063. }
  50064. if (endKey.frame < endFrame) {
  50065. var newKey = {
  50066. frame: endFrame,
  50067. value: endKey.value,
  50068. inTangent: endKey.outTangent,
  50069. outTangent: endKey.outTangent,
  50070. interpolation: endKey.interpolation
  50071. };
  50072. keys.push(newKey);
  50073. }
  50074. }
  50075. this._from = beginFrame;
  50076. this._to = endFrame;
  50077. return this;
  50078. };
  50079. /**
  50080. * Start all animations on given targets
  50081. * @param loop defines if animations must loop
  50082. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50083. * @param from defines the from key (optional)
  50084. * @param to defines the to key (optional)
  50085. * @returns the current animation group
  50086. */
  50087. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50088. var _this = this;
  50089. if (loop === void 0) { loop = false; }
  50090. if (speedRatio === void 0) { speedRatio = 1; }
  50091. if (this._isStarted || this._targetedAnimations.length === 0) {
  50092. return this;
  50093. }
  50094. var _loop_1 = function (targetedAnimation) {
  50095. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50096. animatable.onAnimationEnd = function () {
  50097. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50098. _this._checkAnimationGroupEnded(animatable);
  50099. };
  50100. this_1._animatables.push(animatable);
  50101. };
  50102. var this_1 = this;
  50103. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50104. var targetedAnimation = _a[_i];
  50105. _loop_1(targetedAnimation);
  50106. }
  50107. this._speedRatio = speedRatio;
  50108. this._isStarted = true;
  50109. return this;
  50110. };
  50111. /**
  50112. * Pause all animations
  50113. */
  50114. AnimationGroup.prototype.pause = function () {
  50115. if (!this._isStarted) {
  50116. return this;
  50117. }
  50118. for (var index = 0; index < this._animatables.length; index++) {
  50119. var animatable = this._animatables[index];
  50120. animatable.pause();
  50121. }
  50122. return this;
  50123. };
  50124. /**
  50125. * Play all animations to initial state
  50126. * This function will start() the animations if they were not started or will restart() them if they were paused
  50127. * @param loop defines if animations must loop
  50128. */
  50129. AnimationGroup.prototype.play = function (loop) {
  50130. // only if all animatables are ready and exist
  50131. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50132. if (loop !== undefined) {
  50133. for (var index = 0; index < this._animatables.length; index++) {
  50134. var animatable = this._animatables[index];
  50135. animatable.loopAnimation = loop;
  50136. }
  50137. }
  50138. this.restart();
  50139. }
  50140. else {
  50141. this.stop();
  50142. this.start(loop, this._speedRatio);
  50143. }
  50144. return this;
  50145. };
  50146. /**
  50147. * Reset all animations to initial state
  50148. */
  50149. AnimationGroup.prototype.reset = function () {
  50150. if (!this._isStarted) {
  50151. return this;
  50152. }
  50153. for (var index = 0; index < this._animatables.length; index++) {
  50154. var animatable = this._animatables[index];
  50155. animatable.reset();
  50156. }
  50157. return this;
  50158. };
  50159. /**
  50160. * Restart animations from key 0
  50161. */
  50162. AnimationGroup.prototype.restart = function () {
  50163. if (!this._isStarted) {
  50164. return this;
  50165. }
  50166. for (var index = 0; index < this._animatables.length; index++) {
  50167. var animatable = this._animatables[index];
  50168. animatable.restart();
  50169. }
  50170. return this;
  50171. };
  50172. /**
  50173. * Stop all animations
  50174. */
  50175. AnimationGroup.prototype.stop = function () {
  50176. if (!this._isStarted) {
  50177. return this;
  50178. }
  50179. var list = this._animatables.slice();
  50180. for (var index = 0; index < list.length; index++) {
  50181. list[index].stop();
  50182. }
  50183. this._isStarted = false;
  50184. return this;
  50185. };
  50186. /**
  50187. * Set animation weight for all animatables
  50188. * @param weight defines the weight to use
  50189. * @return the animationGroup
  50190. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50191. */
  50192. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50193. for (var index = 0; index < this._animatables.length; index++) {
  50194. var animatable = this._animatables[index];
  50195. animatable.weight = weight;
  50196. }
  50197. return this;
  50198. };
  50199. /**
  50200. * Synchronize and normalize all animatables with a source animatable
  50201. * @param root defines the root animatable to synchronize with
  50202. * @return the animationGroup
  50203. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50204. */
  50205. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50206. for (var index = 0; index < this._animatables.length; index++) {
  50207. var animatable = this._animatables[index];
  50208. animatable.syncWith(root);
  50209. }
  50210. return this;
  50211. };
  50212. /**
  50213. * Goes to a specific frame in this animation group
  50214. * @param frame the frame number to go to
  50215. * @return the animationGroup
  50216. */
  50217. AnimationGroup.prototype.goToFrame = function (frame) {
  50218. if (!this._isStarted) {
  50219. return this;
  50220. }
  50221. for (var index = 0; index < this._animatables.length; index++) {
  50222. var animatable = this._animatables[index];
  50223. animatable.goToFrame(frame);
  50224. }
  50225. return this;
  50226. };
  50227. /**
  50228. * Dispose all associated resources
  50229. */
  50230. AnimationGroup.prototype.dispose = function () {
  50231. this._targetedAnimations = [];
  50232. this._animatables = [];
  50233. var index = this._scene.animationGroups.indexOf(this);
  50234. if (index > -1) {
  50235. this._scene.animationGroups.splice(index, 1);
  50236. }
  50237. };
  50238. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50239. // animatable should be taken out of the array
  50240. var idx = this._animatables.indexOf(animatable);
  50241. if (idx > -1) {
  50242. this._animatables.splice(idx, 1);
  50243. }
  50244. // all animatables were removed? animation group ended!
  50245. if (this._animatables.length === 0) {
  50246. this._isStarted = false;
  50247. this.onAnimationGroupEndObservable.notifyObservers(this);
  50248. }
  50249. };
  50250. return AnimationGroup;
  50251. }());
  50252. BABYLON.AnimationGroup = AnimationGroup;
  50253. })(BABYLON || (BABYLON = {}));
  50254. //# sourceMappingURL=babylon.animationGroup.js.map
  50255. var BABYLON;
  50256. (function (BABYLON) {
  50257. /**
  50258. * Defines a runtime animation
  50259. */
  50260. var RuntimeAnimation = /** @class */ (function () {
  50261. /**
  50262. * Create a new RuntimeAnimation object
  50263. * @param target defines the target of the animation
  50264. * @param animation defines the source animation object
  50265. * @param scene defines the hosting scene
  50266. * @param host defines the initiating Animatable
  50267. */
  50268. function RuntimeAnimation(target, animation, scene, host) {
  50269. var _this = this;
  50270. this._events = new Array();
  50271. /**
  50272. * The current frame of the runtime animation
  50273. */
  50274. this._currentFrame = 0;
  50275. /**
  50276. * The original value of the runtime animation
  50277. */
  50278. this._originalValue = new Array();
  50279. /**
  50280. * The offsets cache of the runtime animation
  50281. */
  50282. this._offsetsCache = {};
  50283. /**
  50284. * The high limits cache of the runtime animation
  50285. */
  50286. this._highLimitsCache = {};
  50287. /**
  50288. * Specifies if the runtime animation has been stopped
  50289. */
  50290. this._stopped = false;
  50291. /**
  50292. * The blending factor of the runtime animation
  50293. */
  50294. this._blendingFactor = 0;
  50295. /**
  50296. * The target path of the runtime animation
  50297. */
  50298. this._targetPath = "";
  50299. /**
  50300. * The weight of the runtime animation
  50301. */
  50302. this._weight = 1.0;
  50303. /**
  50304. * The ratio offset of the runtime animation
  50305. */
  50306. this._ratioOffset = 0;
  50307. /**
  50308. * The previous delay of the runtime animation
  50309. */
  50310. this._previousDelay = 0;
  50311. /**
  50312. * The previous ratio of the runtime animation
  50313. */
  50314. this._previousRatio = 0;
  50315. this._animation = animation;
  50316. this._target = target;
  50317. this._scene = scene;
  50318. this._host = host;
  50319. animation._runtimeAnimations.push(this);
  50320. // Cloning events locally
  50321. var events = animation.getEvents();
  50322. if (events && events.length > 0) {
  50323. events.forEach(function (e) {
  50324. _this._events.push(e._clone());
  50325. });
  50326. }
  50327. }
  50328. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50329. /**
  50330. * Gets the current frame of the runtime animation
  50331. */
  50332. get: function () {
  50333. return this._currentFrame;
  50334. },
  50335. enumerable: true,
  50336. configurable: true
  50337. });
  50338. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50339. /**
  50340. * Gets the weight of the runtime animation
  50341. */
  50342. get: function () {
  50343. return this._weight;
  50344. },
  50345. enumerable: true,
  50346. configurable: true
  50347. });
  50348. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50349. /**
  50350. * Gets the current value of the runtime animation
  50351. */
  50352. get: function () {
  50353. return this._currentValue;
  50354. },
  50355. enumerable: true,
  50356. configurable: true
  50357. });
  50358. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50359. /**
  50360. * Gets the target path of the runtime animation
  50361. */
  50362. get: function () {
  50363. return this._targetPath;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50369. /**
  50370. * Gets the actual target of the runtime animation
  50371. */
  50372. get: function () {
  50373. return this._activeTarget;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50379. /**
  50380. * Gets the animation from the runtime animation
  50381. */
  50382. get: function () {
  50383. return this._animation;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. /**
  50389. * Resets the runtime animation to the beginning
  50390. * @param restoreOriginal defines whether to restore the target property to the original value
  50391. */
  50392. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50393. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50394. if (restoreOriginal) {
  50395. if (this._target instanceof Array) {
  50396. var index = 0;
  50397. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50398. var target = _a[_i];
  50399. if (this._originalValue[index] !== undefined) {
  50400. this._setValue(target, this._originalValue[index], -1);
  50401. }
  50402. index++;
  50403. }
  50404. }
  50405. else {
  50406. if (this._originalValue[0] !== undefined) {
  50407. this._setValue(this._target, this._originalValue[0], -1);
  50408. }
  50409. }
  50410. }
  50411. this._offsetsCache = {};
  50412. this._highLimitsCache = {};
  50413. this._currentFrame = 0;
  50414. this._blendingFactor = 0;
  50415. this._originalValue = new Array();
  50416. // Events
  50417. for (var index = 0; index < this._events.length; index++) {
  50418. this._events[index].isDone = false;
  50419. }
  50420. };
  50421. /**
  50422. * Specifies if the runtime animation is stopped
  50423. * @returns Boolean specifying if the runtime animation is stopped
  50424. */
  50425. RuntimeAnimation.prototype.isStopped = function () {
  50426. return this._stopped;
  50427. };
  50428. /**
  50429. * Disposes of the runtime animation
  50430. */
  50431. RuntimeAnimation.prototype.dispose = function () {
  50432. var index = this._animation.runtimeAnimations.indexOf(this);
  50433. if (index > -1) {
  50434. this._animation.runtimeAnimations.splice(index, 1);
  50435. }
  50436. };
  50437. /**
  50438. * Interpolates the animation from the current frame
  50439. * @param currentFrame The frame to interpolate the animation to
  50440. * @param repeatCount The number of times that the animation should loop
  50441. * @param loopMode The type of looping mode to use
  50442. * @param offsetValue Animation offset value
  50443. * @param highLimitValue The high limit value
  50444. * @returns The interpolated value
  50445. */
  50446. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50447. this._currentFrame = currentFrame;
  50448. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50449. this._workValue = BABYLON.Matrix.Zero();
  50450. }
  50451. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50452. };
  50453. /**
  50454. * Apply the interpolated value to the target
  50455. * @param currentValue defines the value computed by the animation
  50456. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50457. */
  50458. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50459. if (weight === void 0) { weight = 1.0; }
  50460. if (this._target instanceof Array) {
  50461. var index = 0;
  50462. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50463. var target = _a[_i];
  50464. this._setValue(target, currentValue, weight, index);
  50465. index++;
  50466. }
  50467. }
  50468. else {
  50469. this._setValue(this._target, currentValue, weight);
  50470. }
  50471. };
  50472. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50473. if (targetIndex === void 0) { targetIndex = 0; }
  50474. // Set value
  50475. var path;
  50476. var destination;
  50477. var targetPropertyPath = this._animation.targetPropertyPath;
  50478. if (targetPropertyPath.length > 1) {
  50479. var property = target[targetPropertyPath[0]];
  50480. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50481. property = property[targetPropertyPath[index]];
  50482. }
  50483. path = targetPropertyPath[targetPropertyPath.length - 1];
  50484. destination = property;
  50485. }
  50486. else {
  50487. path = targetPropertyPath[0];
  50488. destination = target;
  50489. }
  50490. this._targetPath = path;
  50491. this._activeTarget = destination;
  50492. this._weight = weight;
  50493. if (this._originalValue[targetIndex] === undefined) {
  50494. var originalValue = void 0;
  50495. if (destination.getRestPose && path === "_matrix") { // For bones
  50496. originalValue = destination.getRestPose();
  50497. }
  50498. else {
  50499. originalValue = destination[path];
  50500. }
  50501. if (originalValue && originalValue.clone) {
  50502. this._originalValue[targetIndex] = originalValue.clone();
  50503. }
  50504. else {
  50505. this._originalValue[targetIndex] = originalValue;
  50506. }
  50507. }
  50508. // Blending
  50509. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50510. if (enableBlending && this._blendingFactor <= 1.0) {
  50511. if (!this._originalBlendValue) {
  50512. var originalValue = destination[path];
  50513. if (originalValue.clone) {
  50514. this._originalBlendValue = originalValue.clone();
  50515. }
  50516. else {
  50517. this._originalBlendValue = originalValue;
  50518. }
  50519. }
  50520. if (this._originalBlendValue.m) { // Matrix
  50521. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50522. if (this._currentValue) {
  50523. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50524. }
  50525. else {
  50526. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50527. }
  50528. }
  50529. else {
  50530. if (this._currentValue) {
  50531. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50532. }
  50533. else {
  50534. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50535. }
  50536. }
  50537. }
  50538. else {
  50539. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50540. }
  50541. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50542. this._blendingFactor += blendingSpeed;
  50543. }
  50544. else {
  50545. this._currentValue = currentValue;
  50546. }
  50547. if (weight !== -1.0) {
  50548. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50549. }
  50550. else {
  50551. destination[path] = this._currentValue;
  50552. }
  50553. if (target.markAsDirty) {
  50554. target.markAsDirty(this._animation.targetProperty);
  50555. }
  50556. };
  50557. /**
  50558. * Gets the loop pmode of the runtime animation
  50559. * @returns Loop Mode
  50560. */
  50561. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50562. if (this._target && this._target.animationPropertiesOverride) {
  50563. return this._target.animationPropertiesOverride.loopMode;
  50564. }
  50565. return this._animation.loopMode;
  50566. };
  50567. /**
  50568. * Move the current animation to a given frame
  50569. * @param frame defines the frame to move to
  50570. */
  50571. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50572. var keys = this._animation.getKeys();
  50573. if (frame < keys[0].frame) {
  50574. frame = keys[0].frame;
  50575. }
  50576. else if (frame > keys[keys.length - 1].frame) {
  50577. frame = keys[keys.length - 1].frame;
  50578. }
  50579. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50580. this.setValue(currentValue, -1);
  50581. };
  50582. /**
  50583. * @hidden Internal use only
  50584. */
  50585. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50586. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50587. this._ratioOffset = this._previousRatio - newRatio;
  50588. };
  50589. /**
  50590. * Execute the current animation
  50591. * @param delay defines the delay to add to the current frame
  50592. * @param from defines the lower bound of the animation range
  50593. * @param to defines the upper bound of the animation range
  50594. * @param loop defines if the current animation must loop
  50595. * @param speedRatio defines the current speed ratio
  50596. * @param weight defines the weight of the animation (default is -1 so no weight)
  50597. * @returns a boolean indicating if the animation is running
  50598. */
  50599. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50600. if (weight === void 0) { weight = -1.0; }
  50601. var targetPropertyPath = this._animation.targetPropertyPath;
  50602. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50603. this._stopped = true;
  50604. return false;
  50605. }
  50606. var returnValue = true;
  50607. var keys = this._animation.getKeys();
  50608. // Adding a start key at frame 0 if missing
  50609. if (keys[0].frame !== 0) {
  50610. var newKey = { frame: 0, value: keys[0].value };
  50611. keys.splice(0, 0, newKey);
  50612. }
  50613. // Adding a duplicate key when there is only one key at frame zero
  50614. else if (keys.length === 1) {
  50615. var newKey = { frame: 0.001, value: keys[0].value };
  50616. keys.push(newKey);
  50617. }
  50618. // Check limits
  50619. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50620. from = keys[0].frame;
  50621. }
  50622. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50623. to = keys[keys.length - 1].frame;
  50624. }
  50625. //to and from cannot be the same key
  50626. if (from === to) {
  50627. if (from > keys[0].frame) {
  50628. from--;
  50629. }
  50630. else if (to < keys[keys.length - 1].frame) {
  50631. to++;
  50632. }
  50633. }
  50634. // Compute ratio
  50635. var range = to - from;
  50636. var offsetValue;
  50637. // ratio represents the frame delta between from and to
  50638. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50639. var highLimitValue = 0;
  50640. this._previousDelay = delay;
  50641. this._previousRatio = ratio;
  50642. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50643. returnValue = false;
  50644. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50645. }
  50646. else {
  50647. // Get max value if required
  50648. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50649. var keyOffset = to.toString() + from.toString();
  50650. if (!this._offsetsCache[keyOffset]) {
  50651. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50652. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50653. switch (this._animation.dataType) {
  50654. // Float
  50655. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50656. this._offsetsCache[keyOffset] = toValue - fromValue;
  50657. break;
  50658. // Quaternion
  50659. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50660. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50661. break;
  50662. // Vector3
  50663. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50664. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50665. // Vector2
  50666. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50667. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50668. // Size
  50669. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50670. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50671. // Color3
  50672. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50673. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50674. default:
  50675. break;
  50676. }
  50677. this._highLimitsCache[keyOffset] = toValue;
  50678. }
  50679. highLimitValue = this._highLimitsCache[keyOffset];
  50680. offsetValue = this._offsetsCache[keyOffset];
  50681. }
  50682. }
  50683. if (offsetValue === undefined) {
  50684. switch (this._animation.dataType) {
  50685. // Float
  50686. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50687. offsetValue = 0;
  50688. break;
  50689. // Quaternion
  50690. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50691. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50692. break;
  50693. // Vector3
  50694. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50695. offsetValue = BABYLON.Vector3.Zero();
  50696. break;
  50697. // Vector2
  50698. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50699. offsetValue = BABYLON.Vector2.Zero();
  50700. break;
  50701. // Size
  50702. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50703. offsetValue = BABYLON.Size.Zero();
  50704. break;
  50705. // Color3
  50706. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50707. offsetValue = BABYLON.Color3.Black();
  50708. }
  50709. }
  50710. // Compute value
  50711. var repeatCount = (ratio / range) >> 0;
  50712. var currentFrame = returnValue ? from + ratio % range : to;
  50713. // Need to normalize?
  50714. if (this._host && this._host.syncRoot) {
  50715. var syncRoot = this._host.syncRoot;
  50716. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50717. currentFrame = from + (to - from) * hostNormalizedFrame;
  50718. }
  50719. // Reset events if looping
  50720. var events = this._events;
  50721. if (range > 0 && this.currentFrame > currentFrame ||
  50722. range < 0 && this.currentFrame < currentFrame) {
  50723. // Need to reset animation events
  50724. for (var index = 0; index < events.length; index++) {
  50725. if (!events[index].onlyOnce) {
  50726. // reset event, the animation is looping
  50727. events[index].isDone = false;
  50728. }
  50729. }
  50730. }
  50731. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50732. // Set value
  50733. this.setValue(currentValue, weight);
  50734. // Check events
  50735. for (var index = 0; index < events.length; index++) {
  50736. // Make sure current frame has passed event frame and that event frame is within the current range
  50737. // Also, handle both forward and reverse animations
  50738. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50739. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50740. var event = events[index];
  50741. if (!event.isDone) {
  50742. // If event should be done only once, remove it.
  50743. if (event.onlyOnce) {
  50744. events.splice(index, 1);
  50745. index--;
  50746. }
  50747. event.isDone = true;
  50748. event.action();
  50749. } // Don't do anything if the event has already be done.
  50750. }
  50751. }
  50752. if (!returnValue) {
  50753. this._stopped = true;
  50754. }
  50755. return returnValue;
  50756. };
  50757. return RuntimeAnimation;
  50758. }());
  50759. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50760. })(BABYLON || (BABYLON = {}));
  50761. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50762. var BABYLON;
  50763. (function (BABYLON) {
  50764. /**
  50765. * Class used to store an actual running animation
  50766. */
  50767. var Animatable = /** @class */ (function () {
  50768. /**
  50769. * Creates a new Animatable
  50770. * @param scene defines the hosting scene
  50771. * @param target defines the target object
  50772. * @param fromFrame defines the starting frame number (default is 0)
  50773. * @param toFrame defines the ending frame number (default is 100)
  50774. * @param loopAnimation defines if the animation must loop (default is false)
  50775. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  50776. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  50777. * @param animations defines a group of animation to add to the new Animatable
  50778. */
  50779. function Animatable(scene,
  50780. /** defines the target object */
  50781. target,
  50782. /** defines the starting frame number (default is 0) */
  50783. fromFrame,
  50784. /** defines the ending frame number (default is 100) */
  50785. toFrame,
  50786. /** defines if the animation must loop (default is false) */
  50787. loopAnimation, speedRatio,
  50788. /** defines a callback to call when animation ends if it is not looping */
  50789. onAnimationEnd, animations) {
  50790. if (fromFrame === void 0) { fromFrame = 0; }
  50791. if (toFrame === void 0) { toFrame = 100; }
  50792. if (loopAnimation === void 0) { loopAnimation = false; }
  50793. if (speedRatio === void 0) { speedRatio = 1.0; }
  50794. this.target = target;
  50795. this.fromFrame = fromFrame;
  50796. this.toFrame = toFrame;
  50797. this.loopAnimation = loopAnimation;
  50798. this.onAnimationEnd = onAnimationEnd;
  50799. this._localDelayOffset = null;
  50800. this._pausedDelay = null;
  50801. this._runtimeAnimations = new Array();
  50802. this._paused = false;
  50803. this._speedRatio = 1;
  50804. this._weight = -1.0;
  50805. /**
  50806. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  50807. * This will only apply for non looping animation (default is true)
  50808. */
  50809. this.disposeOnEnd = true;
  50810. /**
  50811. * Gets a boolean indicating if the animation has started
  50812. */
  50813. this.animationStarted = false;
  50814. /**
  50815. * Observer raised when the animation ends
  50816. */
  50817. this.onAnimationEndObservable = new BABYLON.Observable();
  50818. this._scene = scene;
  50819. if (animations) {
  50820. this.appendAnimations(target, animations);
  50821. }
  50822. this._speedRatio = speedRatio;
  50823. scene._activeAnimatables.push(this);
  50824. }
  50825. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50826. /**
  50827. * Gets the root Animatable used to synchronize and normalize animations
  50828. */
  50829. get: function () {
  50830. return this._syncRoot;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50836. /**
  50837. * Gets the current frame of the first RuntimeAnimation
  50838. * Used to synchronize Animatables
  50839. */
  50840. get: function () {
  50841. if (this._runtimeAnimations.length === 0) {
  50842. return 0;
  50843. }
  50844. return this._runtimeAnimations[0].currentFrame;
  50845. },
  50846. enumerable: true,
  50847. configurable: true
  50848. });
  50849. Object.defineProperty(Animatable.prototype, "weight", {
  50850. /**
  50851. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50852. */
  50853. get: function () {
  50854. return this._weight;
  50855. },
  50856. set: function (value) {
  50857. if (value === -1) { // -1 is ok and means no weight
  50858. this._weight = -1;
  50859. return;
  50860. }
  50861. // Else weight must be in [0, 1] range
  50862. this._weight = Math.min(Math.max(value, 0), 1.0);
  50863. },
  50864. enumerable: true,
  50865. configurable: true
  50866. });
  50867. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50868. /**
  50869. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50870. */
  50871. get: function () {
  50872. return this._speedRatio;
  50873. },
  50874. set: function (value) {
  50875. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50876. var animation = this._runtimeAnimations[index];
  50877. animation._prepareForSpeedRatioChange(value);
  50878. }
  50879. this._speedRatio = value;
  50880. },
  50881. enumerable: true,
  50882. configurable: true
  50883. });
  50884. // Methods
  50885. /**
  50886. * Synchronize and normalize current Animatable with a source Animatable
  50887. * This is useful when using animation weights and when animations are not of the same length
  50888. * @param root defines the root Animatable to synchronize with
  50889. * @returns the current Animatable
  50890. */
  50891. Animatable.prototype.syncWith = function (root) {
  50892. this._syncRoot = root;
  50893. if (root) {
  50894. // Make sure this animatable will animate after the root
  50895. var index = this._scene._activeAnimatables.indexOf(this);
  50896. if (index > -1) {
  50897. this._scene._activeAnimatables.splice(index, 1);
  50898. this._scene._activeAnimatables.push(this);
  50899. }
  50900. }
  50901. return this;
  50902. };
  50903. /**
  50904. * Gets the list of runtime animations
  50905. * @returns an array of RuntimeAnimation
  50906. */
  50907. Animatable.prototype.getAnimations = function () {
  50908. return this._runtimeAnimations;
  50909. };
  50910. /**
  50911. * Adds more animations to the current animatable
  50912. * @param target defines the target of the animations
  50913. * @param animations defines the new animations to add
  50914. */
  50915. Animatable.prototype.appendAnimations = function (target, animations) {
  50916. for (var index = 0; index < animations.length; index++) {
  50917. var animation = animations[index];
  50918. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50919. }
  50920. };
  50921. /**
  50922. * Gets the source animation for a specific property
  50923. * @param property defines the propertyu to look for
  50924. * @returns null or the source animation for the given property
  50925. */
  50926. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50927. var runtimeAnimations = this._runtimeAnimations;
  50928. for (var index = 0; index < runtimeAnimations.length; index++) {
  50929. if (runtimeAnimations[index].animation.targetProperty === property) {
  50930. return runtimeAnimations[index].animation;
  50931. }
  50932. }
  50933. return null;
  50934. };
  50935. /**
  50936. * Gets the runtime animation for a specific property
  50937. * @param property defines the propertyu to look for
  50938. * @returns null or the runtime animation for the given property
  50939. */
  50940. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50941. var runtimeAnimations = this._runtimeAnimations;
  50942. for (var index = 0; index < runtimeAnimations.length; index++) {
  50943. if (runtimeAnimations[index].animation.targetProperty === property) {
  50944. return runtimeAnimations[index];
  50945. }
  50946. }
  50947. return null;
  50948. };
  50949. /**
  50950. * Resets the animatable to its original state
  50951. */
  50952. Animatable.prototype.reset = function () {
  50953. var runtimeAnimations = this._runtimeAnimations;
  50954. for (var index = 0; index < runtimeAnimations.length; index++) {
  50955. runtimeAnimations[index].reset(true);
  50956. }
  50957. this._localDelayOffset = null;
  50958. this._pausedDelay = null;
  50959. };
  50960. /**
  50961. * Allows the animatable to blend with current running animations
  50962. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  50963. * @param blendingSpeed defines the blending speed to use
  50964. */
  50965. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50966. var runtimeAnimations = this._runtimeAnimations;
  50967. for (var index = 0; index < runtimeAnimations.length; index++) {
  50968. runtimeAnimations[index].animation.enableBlending = true;
  50969. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50970. }
  50971. };
  50972. /**
  50973. * Disable animation blending
  50974. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  50975. */
  50976. Animatable.prototype.disableBlending = function () {
  50977. var runtimeAnimations = this._runtimeAnimations;
  50978. for (var index = 0; index < runtimeAnimations.length; index++) {
  50979. runtimeAnimations[index].animation.enableBlending = false;
  50980. }
  50981. };
  50982. /**
  50983. * Jump directly to a given frame
  50984. * @param frame defines the frame to jump to
  50985. */
  50986. Animatable.prototype.goToFrame = function (frame) {
  50987. var runtimeAnimations = this._runtimeAnimations;
  50988. if (runtimeAnimations[0]) {
  50989. var fps = runtimeAnimations[0].animation.framePerSecond;
  50990. var currentFrame = runtimeAnimations[0].currentFrame;
  50991. var adjustTime = frame - currentFrame;
  50992. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50993. if (this._localDelayOffset === null) {
  50994. this._localDelayOffset = 0;
  50995. }
  50996. this._localDelayOffset -= delay;
  50997. }
  50998. for (var index = 0; index < runtimeAnimations.length; index++) {
  50999. runtimeAnimations[index].goToFrame(frame);
  51000. }
  51001. };
  51002. /**
  51003. * Pause the animation
  51004. */
  51005. Animatable.prototype.pause = function () {
  51006. if (this._paused) {
  51007. return;
  51008. }
  51009. this._paused = true;
  51010. };
  51011. /**
  51012. * Restart the animation
  51013. */
  51014. Animatable.prototype.restart = function () {
  51015. this._paused = false;
  51016. };
  51017. Animatable.prototype._raiseOnAnimationEnd = function () {
  51018. if (this.onAnimationEnd) {
  51019. this.onAnimationEnd();
  51020. }
  51021. this.onAnimationEndObservable.notifyObservers(this);
  51022. };
  51023. /**
  51024. * Stop and delete the current animation
  51025. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51026. * @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)
  51027. */
  51028. Animatable.prototype.stop = function (animationName, targetMask) {
  51029. if (animationName || targetMask) {
  51030. var idx = this._scene._activeAnimatables.indexOf(this);
  51031. if (idx > -1) {
  51032. var runtimeAnimations = this._runtimeAnimations;
  51033. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51034. var runtimeAnimation = runtimeAnimations[index];
  51035. if (animationName && runtimeAnimation.animation.name != animationName) {
  51036. continue;
  51037. }
  51038. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51039. continue;
  51040. }
  51041. runtimeAnimation.dispose();
  51042. runtimeAnimations.splice(index, 1);
  51043. }
  51044. if (runtimeAnimations.length == 0) {
  51045. this._scene._activeAnimatables.splice(idx, 1);
  51046. this._raiseOnAnimationEnd();
  51047. }
  51048. }
  51049. }
  51050. else {
  51051. var index = this._scene._activeAnimatables.indexOf(this);
  51052. if (index > -1) {
  51053. this._scene._activeAnimatables.splice(index, 1);
  51054. var runtimeAnimations = this._runtimeAnimations;
  51055. for (var index = 0; index < runtimeAnimations.length; index++) {
  51056. runtimeAnimations[index].dispose();
  51057. }
  51058. this._raiseOnAnimationEnd();
  51059. }
  51060. }
  51061. };
  51062. /**
  51063. * Wait asynchronously for the animation to end
  51064. * @returns a promise which will be fullfilled when the animation ends
  51065. */
  51066. Animatable.prototype.waitAsync = function () {
  51067. var _this = this;
  51068. return new Promise(function (resolve, reject) {
  51069. _this.onAnimationEndObservable.add(function () {
  51070. resolve(_this);
  51071. }, undefined, undefined, _this, true);
  51072. });
  51073. };
  51074. /** @hidden */
  51075. Animatable.prototype._animate = function (delay) {
  51076. if (this._paused) {
  51077. this.animationStarted = false;
  51078. if (this._pausedDelay === null) {
  51079. this._pausedDelay = delay;
  51080. }
  51081. return true;
  51082. }
  51083. if (this._localDelayOffset === null) {
  51084. this._localDelayOffset = delay;
  51085. this._pausedDelay = null;
  51086. }
  51087. else if (this._pausedDelay !== null) {
  51088. this._localDelayOffset += delay - this._pausedDelay;
  51089. this._pausedDelay = null;
  51090. }
  51091. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51092. return true;
  51093. }
  51094. // Animating
  51095. var running = false;
  51096. var runtimeAnimations = this._runtimeAnimations;
  51097. var index;
  51098. for (index = 0; index < runtimeAnimations.length; index++) {
  51099. var animation = runtimeAnimations[index];
  51100. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51101. running = running || isRunning;
  51102. }
  51103. this.animationStarted = running;
  51104. if (!running) {
  51105. if (this.disposeOnEnd) {
  51106. // Remove from active animatables
  51107. index = this._scene._activeAnimatables.indexOf(this);
  51108. this._scene._activeAnimatables.splice(index, 1);
  51109. // Dispose all runtime animations
  51110. for (index = 0; index < runtimeAnimations.length; index++) {
  51111. runtimeAnimations[index].dispose();
  51112. }
  51113. }
  51114. this._raiseOnAnimationEnd();
  51115. if (this.disposeOnEnd) {
  51116. this.onAnimationEnd = null;
  51117. this.onAnimationEndObservable.clear();
  51118. }
  51119. }
  51120. return running;
  51121. };
  51122. return Animatable;
  51123. }());
  51124. BABYLON.Animatable = Animatable;
  51125. })(BABYLON || (BABYLON = {}));
  51126. //# sourceMappingURL=babylon.animatable.js.map
  51127. var BABYLON;
  51128. (function (BABYLON) {
  51129. var EasingFunction = /** @class */ (function () {
  51130. function EasingFunction() {
  51131. // Properties
  51132. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51133. }
  51134. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51135. get: function () {
  51136. return EasingFunction._EASINGMODE_EASEIN;
  51137. },
  51138. enumerable: true,
  51139. configurable: true
  51140. });
  51141. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51142. get: function () {
  51143. return EasingFunction._EASINGMODE_EASEOUT;
  51144. },
  51145. enumerable: true,
  51146. configurable: true
  51147. });
  51148. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51149. get: function () {
  51150. return EasingFunction._EASINGMODE_EASEINOUT;
  51151. },
  51152. enumerable: true,
  51153. configurable: true
  51154. });
  51155. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51156. var n = Math.min(Math.max(easingMode, 0), 2);
  51157. this._easingMode = n;
  51158. };
  51159. EasingFunction.prototype.getEasingMode = function () {
  51160. return this._easingMode;
  51161. };
  51162. EasingFunction.prototype.easeInCore = function (gradient) {
  51163. throw new Error('You must implement this method');
  51164. };
  51165. EasingFunction.prototype.ease = function (gradient) {
  51166. switch (this._easingMode) {
  51167. case EasingFunction.EASINGMODE_EASEIN:
  51168. return this.easeInCore(gradient);
  51169. case EasingFunction.EASINGMODE_EASEOUT:
  51170. return (1 - this.easeInCore(1 - gradient));
  51171. }
  51172. if (gradient >= 0.5) {
  51173. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51174. }
  51175. return (this.easeInCore(gradient * 2) * 0.5);
  51176. };
  51177. //Statics
  51178. EasingFunction._EASINGMODE_EASEIN = 0;
  51179. EasingFunction._EASINGMODE_EASEOUT = 1;
  51180. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51181. return EasingFunction;
  51182. }());
  51183. BABYLON.EasingFunction = EasingFunction;
  51184. var CircleEase = /** @class */ (function (_super) {
  51185. __extends(CircleEase, _super);
  51186. function CircleEase() {
  51187. return _super !== null && _super.apply(this, arguments) || this;
  51188. }
  51189. CircleEase.prototype.easeInCore = function (gradient) {
  51190. gradient = Math.max(0, Math.min(1, gradient));
  51191. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51192. };
  51193. return CircleEase;
  51194. }(EasingFunction));
  51195. BABYLON.CircleEase = CircleEase;
  51196. var BackEase = /** @class */ (function (_super) {
  51197. __extends(BackEase, _super);
  51198. function BackEase(amplitude) {
  51199. if (amplitude === void 0) { amplitude = 1; }
  51200. var _this = _super.call(this) || this;
  51201. _this.amplitude = amplitude;
  51202. return _this;
  51203. }
  51204. BackEase.prototype.easeInCore = function (gradient) {
  51205. var num = Math.max(0, this.amplitude);
  51206. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51207. };
  51208. return BackEase;
  51209. }(EasingFunction));
  51210. BABYLON.BackEase = BackEase;
  51211. var BounceEase = /** @class */ (function (_super) {
  51212. __extends(BounceEase, _super);
  51213. function BounceEase(bounces, bounciness) {
  51214. if (bounces === void 0) { bounces = 3; }
  51215. if (bounciness === void 0) { bounciness = 2; }
  51216. var _this = _super.call(this) || this;
  51217. _this.bounces = bounces;
  51218. _this.bounciness = bounciness;
  51219. return _this;
  51220. }
  51221. BounceEase.prototype.easeInCore = function (gradient) {
  51222. var y = Math.max(0.0, this.bounces);
  51223. var bounciness = this.bounciness;
  51224. if (bounciness <= 1.0) {
  51225. bounciness = 1.001;
  51226. }
  51227. var num9 = Math.pow(bounciness, y);
  51228. var num5 = 1.0 - bounciness;
  51229. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51230. var num15 = gradient * num4;
  51231. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51232. var num3 = Math.floor(num65);
  51233. var num13 = num3 + 1.0;
  51234. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51235. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51236. var num7 = (num8 + num12) * 0.5;
  51237. var num6 = gradient - num7;
  51238. var num2 = num7 - num8;
  51239. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51240. };
  51241. return BounceEase;
  51242. }(EasingFunction));
  51243. BABYLON.BounceEase = BounceEase;
  51244. var CubicEase = /** @class */ (function (_super) {
  51245. __extends(CubicEase, _super);
  51246. function CubicEase() {
  51247. return _super !== null && _super.apply(this, arguments) || this;
  51248. }
  51249. CubicEase.prototype.easeInCore = function (gradient) {
  51250. return (gradient * gradient * gradient);
  51251. };
  51252. return CubicEase;
  51253. }(EasingFunction));
  51254. BABYLON.CubicEase = CubicEase;
  51255. var ElasticEase = /** @class */ (function (_super) {
  51256. __extends(ElasticEase, _super);
  51257. function ElasticEase(oscillations, springiness) {
  51258. if (oscillations === void 0) { oscillations = 3; }
  51259. if (springiness === void 0) { springiness = 3; }
  51260. var _this = _super.call(this) || this;
  51261. _this.oscillations = oscillations;
  51262. _this.springiness = springiness;
  51263. return _this;
  51264. }
  51265. ElasticEase.prototype.easeInCore = function (gradient) {
  51266. var num2;
  51267. var num3 = Math.max(0.0, this.oscillations);
  51268. var num = Math.max(0.0, this.springiness);
  51269. if (num == 0) {
  51270. num2 = gradient;
  51271. }
  51272. else {
  51273. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51274. }
  51275. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51276. };
  51277. return ElasticEase;
  51278. }(EasingFunction));
  51279. BABYLON.ElasticEase = ElasticEase;
  51280. var ExponentialEase = /** @class */ (function (_super) {
  51281. __extends(ExponentialEase, _super);
  51282. function ExponentialEase(exponent) {
  51283. if (exponent === void 0) { exponent = 2; }
  51284. var _this = _super.call(this) || this;
  51285. _this.exponent = exponent;
  51286. return _this;
  51287. }
  51288. ExponentialEase.prototype.easeInCore = function (gradient) {
  51289. if (this.exponent <= 0) {
  51290. return gradient;
  51291. }
  51292. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51293. };
  51294. return ExponentialEase;
  51295. }(EasingFunction));
  51296. BABYLON.ExponentialEase = ExponentialEase;
  51297. var PowerEase = /** @class */ (function (_super) {
  51298. __extends(PowerEase, _super);
  51299. function PowerEase(power) {
  51300. if (power === void 0) { power = 2; }
  51301. var _this = _super.call(this) || this;
  51302. _this.power = power;
  51303. return _this;
  51304. }
  51305. PowerEase.prototype.easeInCore = function (gradient) {
  51306. var y = Math.max(0.0, this.power);
  51307. return Math.pow(gradient, y);
  51308. };
  51309. return PowerEase;
  51310. }(EasingFunction));
  51311. BABYLON.PowerEase = PowerEase;
  51312. var QuadraticEase = /** @class */ (function (_super) {
  51313. __extends(QuadraticEase, _super);
  51314. function QuadraticEase() {
  51315. return _super !== null && _super.apply(this, arguments) || this;
  51316. }
  51317. QuadraticEase.prototype.easeInCore = function (gradient) {
  51318. return (gradient * gradient);
  51319. };
  51320. return QuadraticEase;
  51321. }(EasingFunction));
  51322. BABYLON.QuadraticEase = QuadraticEase;
  51323. var QuarticEase = /** @class */ (function (_super) {
  51324. __extends(QuarticEase, _super);
  51325. function QuarticEase() {
  51326. return _super !== null && _super.apply(this, arguments) || this;
  51327. }
  51328. QuarticEase.prototype.easeInCore = function (gradient) {
  51329. return (gradient * gradient * gradient * gradient);
  51330. };
  51331. return QuarticEase;
  51332. }(EasingFunction));
  51333. BABYLON.QuarticEase = QuarticEase;
  51334. var QuinticEase = /** @class */ (function (_super) {
  51335. __extends(QuinticEase, _super);
  51336. function QuinticEase() {
  51337. return _super !== null && _super.apply(this, arguments) || this;
  51338. }
  51339. QuinticEase.prototype.easeInCore = function (gradient) {
  51340. return (gradient * gradient * gradient * gradient * gradient);
  51341. };
  51342. return QuinticEase;
  51343. }(EasingFunction));
  51344. BABYLON.QuinticEase = QuinticEase;
  51345. var SineEase = /** @class */ (function (_super) {
  51346. __extends(SineEase, _super);
  51347. function SineEase() {
  51348. return _super !== null && _super.apply(this, arguments) || this;
  51349. }
  51350. SineEase.prototype.easeInCore = function (gradient) {
  51351. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51352. };
  51353. return SineEase;
  51354. }(EasingFunction));
  51355. BABYLON.SineEase = SineEase;
  51356. var BezierCurveEase = /** @class */ (function (_super) {
  51357. __extends(BezierCurveEase, _super);
  51358. function BezierCurveEase(x1, y1, x2, y2) {
  51359. if (x1 === void 0) { x1 = 0; }
  51360. if (y1 === void 0) { y1 = 0; }
  51361. if (x2 === void 0) { x2 = 1; }
  51362. if (y2 === void 0) { y2 = 1; }
  51363. var _this = _super.call(this) || this;
  51364. _this.x1 = x1;
  51365. _this.y1 = y1;
  51366. _this.x2 = x2;
  51367. _this.y2 = y2;
  51368. return _this;
  51369. }
  51370. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51371. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51372. };
  51373. return BezierCurveEase;
  51374. }(EasingFunction));
  51375. BABYLON.BezierCurveEase = BezierCurveEase;
  51376. })(BABYLON || (BABYLON = {}));
  51377. //# sourceMappingURL=babylon.easing.js.map
  51378. var BABYLON;
  51379. (function (BABYLON) {
  51380. /**
  51381. * A Condition applied to an Action
  51382. */
  51383. var Condition = /** @class */ (function () {
  51384. /**
  51385. * Creates a new Condition
  51386. * @param actionManager the manager of the action the condition is applied to
  51387. */
  51388. function Condition(actionManager) {
  51389. this._actionManager = actionManager;
  51390. }
  51391. /**
  51392. * Check if the current condition is valid
  51393. * @returns a boolean
  51394. */
  51395. Condition.prototype.isValid = function () {
  51396. return true;
  51397. };
  51398. /**
  51399. * Internal only
  51400. * @hidden
  51401. */
  51402. Condition.prototype._getProperty = function (propertyPath) {
  51403. return this._actionManager._getProperty(propertyPath);
  51404. };
  51405. /**
  51406. * Internal only
  51407. * @hidden
  51408. */
  51409. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51410. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51411. };
  51412. /**
  51413. * Serialize placeholder for child classes
  51414. * @returns the serialized object
  51415. */
  51416. Condition.prototype.serialize = function () {
  51417. };
  51418. /**
  51419. * Internal only
  51420. * @hidden
  51421. */
  51422. Condition.prototype._serialize = function (serializedCondition) {
  51423. return {
  51424. type: 2,
  51425. children: [],
  51426. name: serializedCondition.name,
  51427. properties: serializedCondition.properties
  51428. };
  51429. };
  51430. return Condition;
  51431. }());
  51432. BABYLON.Condition = Condition;
  51433. /**
  51434. * Defines specific conditional operators as extensions of Condition
  51435. */
  51436. var ValueCondition = /** @class */ (function (_super) {
  51437. __extends(ValueCondition, _super);
  51438. /**
  51439. * Creates a new ValueCondition
  51440. * @param actionManager manager for the action the condition applies to
  51441. * @param target for the action
  51442. * @param propertyPath path to specify the property of the target the conditional operator uses
  51443. * @param value the value compared by the conditional operator against the current value of the property
  51444. * @param operator the conditional operator, default ValueCondition.IsEqual
  51445. */
  51446. function ValueCondition(actionManager, target,
  51447. /** path to specify the property of the target the conditional operator uses */
  51448. propertyPath,
  51449. /** the value compared by the conditional operator against the current value of the property */
  51450. value,
  51451. /** the conditional operator, default ValueCondition.IsEqual */
  51452. operator) {
  51453. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51454. var _this = _super.call(this, actionManager) || this;
  51455. _this.propertyPath = propertyPath;
  51456. _this.value = value;
  51457. _this.operator = operator;
  51458. _this._target = target;
  51459. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51460. _this._property = _this._getProperty(_this.propertyPath);
  51461. return _this;
  51462. }
  51463. Object.defineProperty(ValueCondition, "IsEqual", {
  51464. /**
  51465. * returns the number for IsEqual
  51466. */
  51467. get: function () {
  51468. return ValueCondition._IsEqual;
  51469. },
  51470. enumerable: true,
  51471. configurable: true
  51472. });
  51473. Object.defineProperty(ValueCondition, "IsDifferent", {
  51474. /**
  51475. * Returns the number for IsDifferent
  51476. */
  51477. get: function () {
  51478. return ValueCondition._IsDifferent;
  51479. },
  51480. enumerable: true,
  51481. configurable: true
  51482. });
  51483. Object.defineProperty(ValueCondition, "IsGreater", {
  51484. /**
  51485. * Returns the number for IsGreater
  51486. */
  51487. get: function () {
  51488. return ValueCondition._IsGreater;
  51489. },
  51490. enumerable: true,
  51491. configurable: true
  51492. });
  51493. Object.defineProperty(ValueCondition, "IsLesser", {
  51494. /**
  51495. * Returns the number for IsLesser
  51496. */
  51497. get: function () {
  51498. return ValueCondition._IsLesser;
  51499. },
  51500. enumerable: true,
  51501. configurable: true
  51502. });
  51503. /**
  51504. * Compares the given value with the property value for the specified conditional operator
  51505. * @returns the result of the comparison
  51506. */
  51507. ValueCondition.prototype.isValid = function () {
  51508. switch (this.operator) {
  51509. case ValueCondition.IsGreater:
  51510. return this._effectiveTarget[this._property] > this.value;
  51511. case ValueCondition.IsLesser:
  51512. return this._effectiveTarget[this._property] < this.value;
  51513. case ValueCondition.IsEqual:
  51514. case ValueCondition.IsDifferent:
  51515. var check;
  51516. if (this.value.equals) {
  51517. check = this.value.equals(this._effectiveTarget[this._property]);
  51518. }
  51519. else {
  51520. check = this.value === this._effectiveTarget[this._property];
  51521. }
  51522. return this.operator === ValueCondition.IsEqual ? check : !check;
  51523. }
  51524. return false;
  51525. };
  51526. /**
  51527. * Serialize the ValueCondition into a JSON compatible object
  51528. * @returns serialization object
  51529. */
  51530. ValueCondition.prototype.serialize = function () {
  51531. return this._serialize({
  51532. name: "ValueCondition",
  51533. properties: [
  51534. BABYLON.Action._GetTargetProperty(this._target),
  51535. { name: "propertyPath", value: this.propertyPath },
  51536. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51537. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51538. ]
  51539. });
  51540. };
  51541. /**
  51542. * Gets the name of the conditional operator for the ValueCondition
  51543. * @param operator the conditional operator
  51544. * @returns the name
  51545. */
  51546. ValueCondition.GetOperatorName = function (operator) {
  51547. switch (operator) {
  51548. case ValueCondition._IsEqual: return "IsEqual";
  51549. case ValueCondition._IsDifferent: return "IsDifferent";
  51550. case ValueCondition._IsGreater: return "IsGreater";
  51551. case ValueCondition._IsLesser: return "IsLesser";
  51552. default: return "";
  51553. }
  51554. };
  51555. /**
  51556. * Internal only
  51557. * @hidden
  51558. */
  51559. ValueCondition._IsEqual = 0;
  51560. /**
  51561. * Internal only
  51562. * @hidden
  51563. */
  51564. ValueCondition._IsDifferent = 1;
  51565. /**
  51566. * Internal only
  51567. * @hidden
  51568. */
  51569. ValueCondition._IsGreater = 2;
  51570. /**
  51571. * Internal only
  51572. * @hidden
  51573. */
  51574. ValueCondition._IsLesser = 3;
  51575. return ValueCondition;
  51576. }(Condition));
  51577. BABYLON.ValueCondition = ValueCondition;
  51578. /**
  51579. * Defines a predicate condition as an extension of Condition
  51580. */
  51581. var PredicateCondition = /** @class */ (function (_super) {
  51582. __extends(PredicateCondition, _super);
  51583. /**
  51584. * Creates a new PredicateCondition
  51585. * @param actionManager manager for the action the condition applies to
  51586. * @param predicate defines the predicate function used to validate the condition
  51587. */
  51588. function PredicateCondition(actionManager,
  51589. /** defines the predicate function used to validate the condition */
  51590. predicate) {
  51591. var _this = _super.call(this, actionManager) || this;
  51592. _this.predicate = predicate;
  51593. return _this;
  51594. }
  51595. /**
  51596. * @returns the validity of the predicate condition
  51597. */
  51598. PredicateCondition.prototype.isValid = function () {
  51599. return this.predicate();
  51600. };
  51601. return PredicateCondition;
  51602. }(Condition));
  51603. BABYLON.PredicateCondition = PredicateCondition;
  51604. /**
  51605. * Defines a state condition as an extension of Condition
  51606. */
  51607. var StateCondition = /** @class */ (function (_super) {
  51608. __extends(StateCondition, _super);
  51609. /**
  51610. * Creates a new StateCondition
  51611. * @param actionManager manager for the action the condition applies to
  51612. * @param target of the condition
  51613. * @param value to compare with target state
  51614. */
  51615. function StateCondition(actionManager, target, value) {
  51616. var _this = _super.call(this, actionManager) || this;
  51617. _this.value = value;
  51618. _this._target = target;
  51619. return _this;
  51620. }
  51621. /**
  51622. * @returns the validity of the state
  51623. */
  51624. StateCondition.prototype.isValid = function () {
  51625. return this._target.state === this.value;
  51626. };
  51627. /**
  51628. * Serialize the StateCondition into a JSON compatible object
  51629. * @returns serialization object
  51630. */
  51631. StateCondition.prototype.serialize = function () {
  51632. return this._serialize({
  51633. name: "StateCondition",
  51634. properties: [
  51635. BABYLON.Action._GetTargetProperty(this._target),
  51636. { name: "value", value: this.value }
  51637. ]
  51638. });
  51639. };
  51640. return StateCondition;
  51641. }(Condition));
  51642. BABYLON.StateCondition = StateCondition;
  51643. })(BABYLON || (BABYLON = {}));
  51644. //# sourceMappingURL=babylon.condition.js.map
  51645. var BABYLON;
  51646. (function (BABYLON) {
  51647. /**
  51648. * The action to be carried out following a trigger
  51649. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51650. */
  51651. var Action = /** @class */ (function () {
  51652. /**
  51653. * Creates a new Action
  51654. * @param triggerOptions the trigger, with or without parameters, for the action
  51655. * @param condition an optional determinant of action
  51656. */
  51657. function Action(
  51658. /** the trigger, with or without parameters, for the action */
  51659. triggerOptions, condition) {
  51660. this.triggerOptions = triggerOptions;
  51661. /**
  51662. * An event triggered prior to action being executed.
  51663. */
  51664. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51665. if (triggerOptions.parameter) {
  51666. this.trigger = triggerOptions.trigger;
  51667. this._triggerParameter = triggerOptions.parameter;
  51668. }
  51669. else {
  51670. this.trigger = triggerOptions;
  51671. }
  51672. this._nextActiveAction = this;
  51673. this._condition = condition;
  51674. }
  51675. /**
  51676. * Internal only
  51677. * @hidden
  51678. */
  51679. Action.prototype._prepare = function () {
  51680. };
  51681. /**
  51682. * Gets the trigger parameters
  51683. * @returns the trigger parameters
  51684. */
  51685. Action.prototype.getTriggerParameter = function () {
  51686. return this._triggerParameter;
  51687. };
  51688. /**
  51689. * Internal only - executes current action event
  51690. * @hidden
  51691. */
  51692. Action.prototype._executeCurrent = function (evt) {
  51693. if (this._nextActiveAction._condition) {
  51694. var condition = this._nextActiveAction._condition;
  51695. var currentRenderId = this._actionManager.getScene().getRenderId();
  51696. // We cache the current evaluation for the current frame
  51697. if (condition._evaluationId === currentRenderId) {
  51698. if (!condition._currentResult) {
  51699. return;
  51700. }
  51701. }
  51702. else {
  51703. condition._evaluationId = currentRenderId;
  51704. if (!condition.isValid()) {
  51705. condition._currentResult = false;
  51706. return;
  51707. }
  51708. condition._currentResult = true;
  51709. }
  51710. }
  51711. this.onBeforeExecuteObservable.notifyObservers(this);
  51712. this._nextActiveAction.execute(evt);
  51713. this.skipToNextActiveAction();
  51714. };
  51715. /**
  51716. * Execute placeholder for child classes
  51717. * @param evt optional action event
  51718. */
  51719. Action.prototype.execute = function (evt) {
  51720. };
  51721. /**
  51722. * Skips to next active action
  51723. */
  51724. Action.prototype.skipToNextActiveAction = function () {
  51725. if (this._nextActiveAction._child) {
  51726. if (!this._nextActiveAction._child._actionManager) {
  51727. this._nextActiveAction._child._actionManager = this._actionManager;
  51728. }
  51729. this._nextActiveAction = this._nextActiveAction._child;
  51730. }
  51731. else {
  51732. this._nextActiveAction = this;
  51733. }
  51734. };
  51735. /**
  51736. * Adds action to chain of actions, may be a DoNothingAction
  51737. * @param action defines the next action to execute
  51738. * @returns The action passed in
  51739. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51740. */
  51741. Action.prototype.then = function (action) {
  51742. this._child = action;
  51743. action._actionManager = this._actionManager;
  51744. action._prepare();
  51745. return action;
  51746. };
  51747. /**
  51748. * Internal only
  51749. * @hidden
  51750. */
  51751. Action.prototype._getProperty = function (propertyPath) {
  51752. return this._actionManager._getProperty(propertyPath);
  51753. };
  51754. /**
  51755. * Internal only
  51756. * @hidden
  51757. */
  51758. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51759. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51760. };
  51761. /**
  51762. * Serialize placeholder for child classes
  51763. * @param parent of child
  51764. * @returns the serialized object
  51765. */
  51766. Action.prototype.serialize = function (parent) {
  51767. };
  51768. /**
  51769. * Internal only called by serialize
  51770. * @hidden
  51771. */
  51772. Action.prototype._serialize = function (serializedAction, parent) {
  51773. var serializationObject = {
  51774. type: 1,
  51775. children: [],
  51776. name: serializedAction.name,
  51777. properties: serializedAction.properties || []
  51778. };
  51779. // Serialize child
  51780. if (this._child) {
  51781. this._child.serialize(serializationObject);
  51782. }
  51783. // Check if "this" has a condition
  51784. if (this._condition) {
  51785. var serializedCondition = this._condition.serialize();
  51786. serializedCondition.children.push(serializationObject);
  51787. if (parent) {
  51788. parent.children.push(serializedCondition);
  51789. }
  51790. return serializedCondition;
  51791. }
  51792. if (parent) {
  51793. parent.children.push(serializationObject);
  51794. }
  51795. return serializationObject;
  51796. };
  51797. /**
  51798. * Internal only
  51799. * @hidden
  51800. */
  51801. Action._SerializeValueAsString = function (value) {
  51802. if (typeof value === "number") {
  51803. return value.toString();
  51804. }
  51805. if (typeof value === "boolean") {
  51806. return value ? "true" : "false";
  51807. }
  51808. if (value instanceof BABYLON.Vector2) {
  51809. return value.x + ", " + value.y;
  51810. }
  51811. if (value instanceof BABYLON.Vector3) {
  51812. return value.x + ", " + value.y + ", " + value.z;
  51813. }
  51814. if (value instanceof BABYLON.Color3) {
  51815. return value.r + ", " + value.g + ", " + value.b;
  51816. }
  51817. if (value instanceof BABYLON.Color4) {
  51818. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51819. }
  51820. return value; // string
  51821. };
  51822. /**
  51823. * Internal only
  51824. * @hidden
  51825. */
  51826. Action._GetTargetProperty = function (target) {
  51827. return {
  51828. name: "target",
  51829. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51830. : target instanceof BABYLON.Light ? "LightProperties"
  51831. : target instanceof BABYLON.Camera ? "CameraProperties"
  51832. : "SceneProperties",
  51833. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51834. };
  51835. };
  51836. return Action;
  51837. }());
  51838. BABYLON.Action = Action;
  51839. })(BABYLON || (BABYLON = {}));
  51840. //# sourceMappingURL=babylon.action.js.map
  51841. var BABYLON;
  51842. (function (BABYLON) {
  51843. /**
  51844. * ActionEvent is the event being sent when an action is triggered.
  51845. */
  51846. var ActionEvent = /** @class */ (function () {
  51847. /**
  51848. * Creates a new ActionEvent
  51849. * @param source The mesh or sprite that triggered the action
  51850. * @param pointerX The X mouse cursor position at the time of the event
  51851. * @param pointerY The Y mouse cursor position at the time of the event
  51852. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51853. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51854. * @param additionalData additional data for the event
  51855. */
  51856. function ActionEvent(
  51857. /** The mesh or sprite that triggered the action */
  51858. source,
  51859. /** The X mouse cursor position at the time of the event */
  51860. pointerX,
  51861. /** The Y mouse cursor position at the time of the event */
  51862. pointerY,
  51863. /** The mesh that is currently pointed at (can be null) */
  51864. meshUnderPointer,
  51865. /** the original (browser) event that triggered the ActionEvent */
  51866. sourceEvent,
  51867. /** additional data for the event */
  51868. additionalData) {
  51869. this.source = source;
  51870. this.pointerX = pointerX;
  51871. this.pointerY = pointerY;
  51872. this.meshUnderPointer = meshUnderPointer;
  51873. this.sourceEvent = sourceEvent;
  51874. this.additionalData = additionalData;
  51875. }
  51876. /**
  51877. * Helper function to auto-create an ActionEvent from a source mesh.
  51878. * @param source The source mesh that triggered the event
  51879. * @param evt The original (browser) event
  51880. * @param additionalData additional data for the event
  51881. * @returns the new ActionEvent
  51882. */
  51883. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51884. var scene = source.getScene();
  51885. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51886. };
  51887. /**
  51888. * Helper function to auto-create an ActionEvent from a source sprite
  51889. * @param source The source sprite that triggered the event
  51890. * @param scene Scene associated with the sprite
  51891. * @param evt The original (browser) event
  51892. * @param additionalData additional data for the event
  51893. * @returns the new ActionEvent
  51894. */
  51895. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51896. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51897. };
  51898. /**
  51899. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51900. * @param scene the scene where the event occurred
  51901. * @param evt The original (browser) event
  51902. * @returns the new ActionEvent
  51903. */
  51904. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51905. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51906. };
  51907. /**
  51908. * Helper function to auto-create an ActionEvent from a primitive
  51909. * @param prim defines the target primitive
  51910. * @param pointerPos defines the pointer position
  51911. * @param evt The original (browser) event
  51912. * @param additionalData additional data for the event
  51913. * @returns the new ActionEvent
  51914. */
  51915. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51916. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51917. };
  51918. return ActionEvent;
  51919. }());
  51920. BABYLON.ActionEvent = ActionEvent;
  51921. /**
  51922. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51923. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51924. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  51925. */
  51926. var ActionManager = /** @class */ (function () {
  51927. /**
  51928. * Creates a new action manager
  51929. * @param scene defines the hosting scene
  51930. */
  51931. function ActionManager(scene) {
  51932. // Members
  51933. /** Gets the list of actions */
  51934. this.actions = new Array();
  51935. /** Gets the cursor to use when hovering items */
  51936. this.hoverCursor = '';
  51937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51938. scene.actionManagers.push(this);
  51939. }
  51940. Object.defineProperty(ActionManager, "NothingTrigger", {
  51941. /**
  51942. * Nothing
  51943. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51944. */
  51945. get: function () {
  51946. return ActionManager._NothingTrigger;
  51947. },
  51948. enumerable: true,
  51949. configurable: true
  51950. });
  51951. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51952. /**
  51953. * On pick
  51954. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51955. */
  51956. get: function () {
  51957. return ActionManager._OnPickTrigger;
  51958. },
  51959. enumerable: true,
  51960. configurable: true
  51961. });
  51962. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51963. /**
  51964. * On left pick
  51965. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51966. */
  51967. get: function () {
  51968. return ActionManager._OnLeftPickTrigger;
  51969. },
  51970. enumerable: true,
  51971. configurable: true
  51972. });
  51973. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51974. /**
  51975. * On right pick
  51976. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51977. */
  51978. get: function () {
  51979. return ActionManager._OnRightPickTrigger;
  51980. },
  51981. enumerable: true,
  51982. configurable: true
  51983. });
  51984. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51985. /**
  51986. * On center pick
  51987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51988. */
  51989. get: function () {
  51990. return ActionManager._OnCenterPickTrigger;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51996. /**
  51997. * On pick down
  51998. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51999. */
  52000. get: function () {
  52001. return ActionManager._OnPickDownTrigger;
  52002. },
  52003. enumerable: true,
  52004. configurable: true
  52005. });
  52006. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52007. /**
  52008. * On double pick
  52009. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52010. */
  52011. get: function () {
  52012. return ActionManager._OnDoublePickTrigger;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52018. /**
  52019. * On pick up
  52020. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52021. */
  52022. get: function () {
  52023. return ActionManager._OnPickUpTrigger;
  52024. },
  52025. enumerable: true,
  52026. configurable: true
  52027. });
  52028. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52029. /**
  52030. * On pick out.
  52031. * This trigger will only be raised if you also declared a OnPickDown
  52032. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52033. */
  52034. get: function () {
  52035. return ActionManager._OnPickOutTrigger;
  52036. },
  52037. enumerable: true,
  52038. configurable: true
  52039. });
  52040. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52041. /**
  52042. * On long press
  52043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52044. */
  52045. get: function () {
  52046. return ActionManager._OnLongPressTrigger;
  52047. },
  52048. enumerable: true,
  52049. configurable: true
  52050. });
  52051. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52052. /**
  52053. * On pointer over
  52054. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52055. */
  52056. get: function () {
  52057. return ActionManager._OnPointerOverTrigger;
  52058. },
  52059. enumerable: true,
  52060. configurable: true
  52061. });
  52062. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52063. /**
  52064. * On pointer out
  52065. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52066. */
  52067. get: function () {
  52068. return ActionManager._OnPointerOutTrigger;
  52069. },
  52070. enumerable: true,
  52071. configurable: true
  52072. });
  52073. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52074. /**
  52075. * On every frame
  52076. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52077. */
  52078. get: function () {
  52079. return ActionManager._OnEveryFrameTrigger;
  52080. },
  52081. enumerable: true,
  52082. configurable: true
  52083. });
  52084. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52085. /**
  52086. * On intersection enter
  52087. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52088. */
  52089. get: function () {
  52090. return ActionManager._OnIntersectionEnterTrigger;
  52091. },
  52092. enumerable: true,
  52093. configurable: true
  52094. });
  52095. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52096. /**
  52097. * On intersection exit
  52098. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52099. */
  52100. get: function () {
  52101. return ActionManager._OnIntersectionExitTrigger;
  52102. },
  52103. enumerable: true,
  52104. configurable: true
  52105. });
  52106. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52107. /**
  52108. * On key down
  52109. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52110. */
  52111. get: function () {
  52112. return ActionManager._OnKeyDownTrigger;
  52113. },
  52114. enumerable: true,
  52115. configurable: true
  52116. });
  52117. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52118. /**
  52119. * On key up
  52120. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52121. */
  52122. get: function () {
  52123. return ActionManager._OnKeyUpTrigger;
  52124. },
  52125. enumerable: true,
  52126. configurable: true
  52127. });
  52128. // Methods
  52129. /**
  52130. * Releases all associated resources
  52131. */
  52132. ActionManager.prototype.dispose = function () {
  52133. var index = this._scene.actionManagers.indexOf(this);
  52134. for (var i = 0; i < this.actions.length; i++) {
  52135. var action = this.actions[i];
  52136. ActionManager.Triggers[action.trigger]--;
  52137. if (ActionManager.Triggers[action.trigger] === 0) {
  52138. delete ActionManager.Triggers[action.trigger];
  52139. }
  52140. }
  52141. if (index > -1) {
  52142. this._scene.actionManagers.splice(index, 1);
  52143. }
  52144. };
  52145. /**
  52146. * Gets hosting scene
  52147. * @returns the hosting scene
  52148. */
  52149. ActionManager.prototype.getScene = function () {
  52150. return this._scene;
  52151. };
  52152. /**
  52153. * Does this action manager handles actions of any of the given triggers
  52154. * @param triggers defines the triggers to be tested
  52155. * @return a boolean indicating whether one (or more) of the triggers is handled
  52156. */
  52157. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52158. for (var index = 0; index < this.actions.length; index++) {
  52159. var action = this.actions[index];
  52160. if (triggers.indexOf(action.trigger) > -1) {
  52161. return true;
  52162. }
  52163. }
  52164. return false;
  52165. };
  52166. /**
  52167. * Does this action manager handles actions of a given trigger
  52168. * @param trigger defines the trigger to be tested
  52169. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52170. * @return whether the trigger is handled
  52171. */
  52172. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52173. for (var index = 0; index < this.actions.length; index++) {
  52174. var action = this.actions[index];
  52175. if (action.trigger === trigger) {
  52176. if (parameterPredicate) {
  52177. if (parameterPredicate(action.getTriggerParameter())) {
  52178. return true;
  52179. }
  52180. }
  52181. else {
  52182. return true;
  52183. }
  52184. }
  52185. }
  52186. return false;
  52187. };
  52188. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52189. /**
  52190. * Does this action manager has pointer triggers
  52191. */
  52192. get: function () {
  52193. for (var index = 0; index < this.actions.length; index++) {
  52194. var action = this.actions[index];
  52195. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52196. return true;
  52197. }
  52198. }
  52199. return false;
  52200. },
  52201. enumerable: true,
  52202. configurable: true
  52203. });
  52204. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52205. /**
  52206. * Does this action manager has pick triggers
  52207. */
  52208. get: function () {
  52209. for (var index = 0; index < this.actions.length; index++) {
  52210. var action = this.actions[index];
  52211. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52212. return true;
  52213. }
  52214. }
  52215. return false;
  52216. },
  52217. enumerable: true,
  52218. configurable: true
  52219. });
  52220. Object.defineProperty(ActionManager, "HasTriggers", {
  52221. /**
  52222. * Does exist one action manager with at least one trigger
  52223. **/
  52224. get: function () {
  52225. for (var t in ActionManager.Triggers) {
  52226. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52227. return true;
  52228. }
  52229. }
  52230. return false;
  52231. },
  52232. enumerable: true,
  52233. configurable: true
  52234. });
  52235. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52236. /**
  52237. * Does exist one action manager with at least one pick trigger
  52238. **/
  52239. get: function () {
  52240. for (var t in ActionManager.Triggers) {
  52241. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52242. var t_int = parseInt(t);
  52243. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52244. return true;
  52245. }
  52246. }
  52247. }
  52248. return false;
  52249. },
  52250. enumerable: true,
  52251. configurable: true
  52252. });
  52253. /**
  52254. * Does exist one action manager that handles actions of a given trigger
  52255. * @param trigger defines the trigger to be tested
  52256. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52257. **/
  52258. ActionManager.HasSpecificTrigger = function (trigger) {
  52259. for (var t in ActionManager.Triggers) {
  52260. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52261. var t_int = parseInt(t);
  52262. if (t_int === trigger) {
  52263. return true;
  52264. }
  52265. }
  52266. }
  52267. return false;
  52268. };
  52269. /**
  52270. * Registers an action to this action manager
  52271. * @param action defines the action to be registered
  52272. * @return the action amended (prepared) after registration
  52273. */
  52274. ActionManager.prototype.registerAction = function (action) {
  52275. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52276. if (this.getScene().actionManager !== this) {
  52277. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52278. return null;
  52279. }
  52280. }
  52281. this.actions.push(action);
  52282. if (ActionManager.Triggers[action.trigger]) {
  52283. ActionManager.Triggers[action.trigger]++;
  52284. }
  52285. else {
  52286. ActionManager.Triggers[action.trigger] = 1;
  52287. }
  52288. action._actionManager = this;
  52289. action._prepare();
  52290. return action;
  52291. };
  52292. /**
  52293. * Unregisters an action to this action manager
  52294. * @param action defines the action to be unregistered
  52295. * @return a boolean indicating whether the action has been unregistered
  52296. */
  52297. ActionManager.prototype.unregisterAction = function (action) {
  52298. var index = this.actions.indexOf(action);
  52299. if (index !== -1) {
  52300. this.actions.splice(index, 1);
  52301. ActionManager.Triggers[action.trigger] -= 1;
  52302. if (ActionManager.Triggers[action.trigger] === 0) {
  52303. delete ActionManager.Triggers[action.trigger];
  52304. }
  52305. delete action._actionManager;
  52306. return true;
  52307. }
  52308. return false;
  52309. };
  52310. /**
  52311. * Process a specific trigger
  52312. * @param trigger defines the trigger to process
  52313. * @param evt defines the event details to be processed
  52314. */
  52315. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52316. for (var index = 0; index < this.actions.length; index++) {
  52317. var action = this.actions[index];
  52318. if (action.trigger === trigger) {
  52319. if (evt) {
  52320. if (trigger === ActionManager.OnKeyUpTrigger
  52321. || trigger === ActionManager.OnKeyDownTrigger) {
  52322. var parameter = action.getTriggerParameter();
  52323. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52324. if (!parameter.toLowerCase) {
  52325. continue;
  52326. }
  52327. var lowerCase = parameter.toLowerCase();
  52328. if (lowerCase !== evt.sourceEvent.key) {
  52329. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52330. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52331. if (actualkey !== lowerCase) {
  52332. continue;
  52333. }
  52334. }
  52335. }
  52336. }
  52337. }
  52338. action._executeCurrent(evt);
  52339. }
  52340. }
  52341. };
  52342. /** @hidden */
  52343. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52344. var properties = propertyPath.split(".");
  52345. for (var index = 0; index < properties.length - 1; index++) {
  52346. target = target[properties[index]];
  52347. }
  52348. return target;
  52349. };
  52350. /** @hidden */
  52351. ActionManager.prototype._getProperty = function (propertyPath) {
  52352. var properties = propertyPath.split(".");
  52353. return properties[properties.length - 1];
  52354. };
  52355. /**
  52356. * Serialize this manager to a JSON object
  52357. * @param name defines the property name to store this manager
  52358. * @returns a JSON representation of this manager
  52359. */
  52360. ActionManager.prototype.serialize = function (name) {
  52361. var root = {
  52362. children: new Array(),
  52363. name: name,
  52364. type: 3,
  52365. properties: new Array() // Empty for root but required
  52366. };
  52367. for (var i = 0; i < this.actions.length; i++) {
  52368. var triggerObject = {
  52369. type: 0,
  52370. children: new Array(),
  52371. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52372. properties: new Array()
  52373. };
  52374. var triggerOptions = this.actions[i].triggerOptions;
  52375. if (triggerOptions && typeof triggerOptions !== "number") {
  52376. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52377. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52378. }
  52379. else {
  52380. var parameter = {};
  52381. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52382. if (triggerOptions.parameter.mesh) {
  52383. parameter._meshId = triggerOptions.parameter.mesh.id;
  52384. }
  52385. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52386. }
  52387. }
  52388. // Serialize child action, recursively
  52389. this.actions[i].serialize(triggerObject);
  52390. // Add serialized trigger
  52391. root.children.push(triggerObject);
  52392. }
  52393. return root;
  52394. };
  52395. /**
  52396. * Creates a new ActionManager from a JSON data
  52397. * @param parsedActions defines the JSON data to read from
  52398. * @param object defines the hosting mesh
  52399. * @param scene defines the hosting scene
  52400. */
  52401. ActionManager.Parse = function (parsedActions, object, scene) {
  52402. var actionManager = new ActionManager(scene);
  52403. if (object === null)
  52404. scene.actionManager = actionManager;
  52405. else
  52406. object.actionManager = actionManager;
  52407. // instanciate a new object
  52408. var instanciate = function (name, params) {
  52409. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52410. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52411. newInstance.constructor.apply(newInstance, params);
  52412. return newInstance;
  52413. };
  52414. var parseParameter = function (name, value, target, propertyPath) {
  52415. if (propertyPath === null) {
  52416. // String, boolean or float
  52417. var floatValue = parseFloat(value);
  52418. if (value === "true" || value === "false")
  52419. return value === "true";
  52420. else
  52421. return isNaN(floatValue) ? value : floatValue;
  52422. }
  52423. var effectiveTarget = propertyPath.split(".");
  52424. var values = value.split(",");
  52425. // Get effective Target
  52426. for (var i = 0; i < effectiveTarget.length; i++) {
  52427. target = target[effectiveTarget[i]];
  52428. }
  52429. // Return appropriate value with its type
  52430. if (typeof (target) === "boolean")
  52431. return values[0] === "true";
  52432. if (typeof (target) === "string")
  52433. return values[0];
  52434. // Parameters with multiple values such as Vector3 etc.
  52435. var split = new Array();
  52436. for (var i = 0; i < values.length; i++)
  52437. split.push(parseFloat(values[i]));
  52438. if (target instanceof BABYLON.Vector3)
  52439. return BABYLON.Vector3.FromArray(split);
  52440. if (target instanceof BABYLON.Vector4)
  52441. return BABYLON.Vector4.FromArray(split);
  52442. if (target instanceof BABYLON.Color3)
  52443. return BABYLON.Color3.FromArray(split);
  52444. if (target instanceof BABYLON.Color4)
  52445. return BABYLON.Color4.FromArray(split);
  52446. return parseFloat(values[0]);
  52447. };
  52448. // traverse graph per trigger
  52449. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52450. if (combineArray === void 0) { combineArray = null; }
  52451. if (parsedAction.detached)
  52452. return;
  52453. var parameters = new Array();
  52454. var target = null;
  52455. var propertyPath = null;
  52456. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52457. // Parameters
  52458. if (parsedAction.type === 2)
  52459. parameters.push(actionManager);
  52460. else
  52461. parameters.push(trigger);
  52462. if (combine) {
  52463. var actions = new Array();
  52464. for (var j = 0; j < parsedAction.combine.length; j++) {
  52465. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52466. }
  52467. parameters.push(actions);
  52468. }
  52469. else {
  52470. for (var i = 0; i < parsedAction.properties.length; i++) {
  52471. var value = parsedAction.properties[i].value;
  52472. var name = parsedAction.properties[i].name;
  52473. var targetType = parsedAction.properties[i].targetType;
  52474. if (name === "target")
  52475. if (targetType !== null && targetType === "SceneProperties")
  52476. value = target = scene;
  52477. else
  52478. value = target = scene.getNodeByName(value);
  52479. else if (name === "parent")
  52480. value = scene.getNodeByName(value);
  52481. else if (name === "sound")
  52482. value = scene.getSoundByName(value);
  52483. else if (name !== "propertyPath") {
  52484. if (parsedAction.type === 2 && name === "operator")
  52485. value = BABYLON.ValueCondition[value];
  52486. else
  52487. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52488. }
  52489. else {
  52490. propertyPath = value;
  52491. }
  52492. parameters.push(value);
  52493. }
  52494. }
  52495. if (combineArray === null) {
  52496. parameters.push(condition);
  52497. }
  52498. else {
  52499. parameters.push(null);
  52500. }
  52501. // If interpolate value action
  52502. if (parsedAction.name === "InterpolateValueAction") {
  52503. var param = parameters[parameters.length - 2];
  52504. parameters[parameters.length - 1] = param;
  52505. parameters[parameters.length - 2] = condition;
  52506. }
  52507. // Action or condition(s) and not CombineAction
  52508. var newAction = instanciate(parsedAction.name, parameters);
  52509. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52510. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52511. if (action)
  52512. action.then(nothing);
  52513. else
  52514. actionManager.registerAction(nothing);
  52515. action = nothing;
  52516. }
  52517. if (combineArray === null) {
  52518. if (newAction instanceof BABYLON.Condition) {
  52519. condition = newAction;
  52520. newAction = action;
  52521. }
  52522. else {
  52523. condition = null;
  52524. if (action)
  52525. action.then(newAction);
  52526. else
  52527. actionManager.registerAction(newAction);
  52528. }
  52529. }
  52530. else {
  52531. combineArray.push(newAction);
  52532. }
  52533. for (var i = 0; i < parsedAction.children.length; i++)
  52534. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52535. };
  52536. // triggers
  52537. for (var i = 0; i < parsedActions.children.length; i++) {
  52538. var triggerParams;
  52539. var trigger = parsedActions.children[i];
  52540. if (trigger.properties.length > 0) {
  52541. var param = trigger.properties[0].value;
  52542. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52543. if (value._meshId) {
  52544. value.mesh = scene.getMeshByID(value._meshId);
  52545. }
  52546. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52547. }
  52548. else
  52549. triggerParams = ActionManager[trigger.name];
  52550. for (var j = 0; j < trigger.children.length; j++) {
  52551. if (!trigger.detached)
  52552. traverse(trigger.children[j], triggerParams, null, null);
  52553. }
  52554. }
  52555. };
  52556. /**
  52557. * Get a trigger name by index
  52558. * @param trigger defines the trigger index
  52559. * @returns a trigger name
  52560. */
  52561. ActionManager.GetTriggerName = function (trigger) {
  52562. switch (trigger) {
  52563. case 0: return "NothingTrigger";
  52564. case 1: return "OnPickTrigger";
  52565. case 2: return "OnLeftPickTrigger";
  52566. case 3: return "OnRightPickTrigger";
  52567. case 4: return "OnCenterPickTrigger";
  52568. case 5: return "OnPickDownTrigger";
  52569. case 6: return "OnPickUpTrigger";
  52570. case 7: return "OnLongPressTrigger";
  52571. case 8: return "OnPointerOverTrigger";
  52572. case 9: return "OnPointerOutTrigger";
  52573. case 10: return "OnEveryFrameTrigger";
  52574. case 11: return "OnIntersectionEnterTrigger";
  52575. case 12: return "OnIntersectionExitTrigger";
  52576. case 13: return "OnKeyDownTrigger";
  52577. case 14: return "OnKeyUpTrigger";
  52578. case 15: return "OnPickOutTrigger";
  52579. default: return "";
  52580. }
  52581. };
  52582. // Statics
  52583. ActionManager._NothingTrigger = 0;
  52584. ActionManager._OnPickTrigger = 1;
  52585. ActionManager._OnLeftPickTrigger = 2;
  52586. ActionManager._OnRightPickTrigger = 3;
  52587. ActionManager._OnCenterPickTrigger = 4;
  52588. ActionManager._OnPickDownTrigger = 5;
  52589. ActionManager._OnDoublePickTrigger = 6;
  52590. ActionManager._OnPickUpTrigger = 7;
  52591. ActionManager._OnLongPressTrigger = 8;
  52592. ActionManager._OnPointerOverTrigger = 9;
  52593. ActionManager._OnPointerOutTrigger = 10;
  52594. ActionManager._OnEveryFrameTrigger = 11;
  52595. ActionManager._OnIntersectionEnterTrigger = 12;
  52596. ActionManager._OnIntersectionExitTrigger = 13;
  52597. ActionManager._OnKeyDownTrigger = 14;
  52598. ActionManager._OnKeyUpTrigger = 15;
  52599. ActionManager._OnPickOutTrigger = 16;
  52600. /** Gets the list of active triggers */
  52601. ActionManager.Triggers = {};
  52602. return ActionManager;
  52603. }());
  52604. BABYLON.ActionManager = ActionManager;
  52605. })(BABYLON || (BABYLON = {}));
  52606. //# sourceMappingURL=babylon.actionManager.js.map
  52607. var BABYLON;
  52608. (function (BABYLON) {
  52609. var InterpolateValueAction = /** @class */ (function (_super) {
  52610. __extends(InterpolateValueAction, _super);
  52611. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52612. if (duration === void 0) { duration = 1000; }
  52613. var _this = _super.call(this, triggerOptions, condition) || this;
  52614. _this.propertyPath = propertyPath;
  52615. _this.value = value;
  52616. _this.duration = duration;
  52617. _this.stopOtherAnimations = stopOtherAnimations;
  52618. _this.onInterpolationDone = onInterpolationDone;
  52619. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52620. _this._target = _this._effectiveTarget = target;
  52621. return _this;
  52622. }
  52623. InterpolateValueAction.prototype._prepare = function () {
  52624. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52625. this._property = this._getProperty(this.propertyPath);
  52626. };
  52627. InterpolateValueAction.prototype.execute = function () {
  52628. var _this = this;
  52629. var scene = this._actionManager.getScene();
  52630. var keys = [
  52631. {
  52632. frame: 0,
  52633. value: this._effectiveTarget[this._property]
  52634. }, {
  52635. frame: 100,
  52636. value: this.value
  52637. }
  52638. ];
  52639. var dataType;
  52640. if (typeof this.value === "number") {
  52641. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52642. }
  52643. else if (this.value instanceof BABYLON.Color3) {
  52644. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52645. }
  52646. else if (this.value instanceof BABYLON.Vector3) {
  52647. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52648. }
  52649. else if (this.value instanceof BABYLON.Matrix) {
  52650. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52651. }
  52652. else if (this.value instanceof BABYLON.Quaternion) {
  52653. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52654. }
  52655. else {
  52656. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52657. return;
  52658. }
  52659. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52660. animation.setKeys(keys);
  52661. if (this.stopOtherAnimations) {
  52662. scene.stopAnimation(this._effectiveTarget);
  52663. }
  52664. var wrapper = function () {
  52665. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52666. if (_this.onInterpolationDone) {
  52667. _this.onInterpolationDone();
  52668. }
  52669. };
  52670. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52671. };
  52672. InterpolateValueAction.prototype.serialize = function (parent) {
  52673. return _super.prototype._serialize.call(this, {
  52674. name: "InterpolateValueAction",
  52675. properties: [
  52676. BABYLON.Action._GetTargetProperty(this._target),
  52677. { name: "propertyPath", value: this.propertyPath },
  52678. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52679. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52680. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52681. ]
  52682. }, parent);
  52683. };
  52684. return InterpolateValueAction;
  52685. }(BABYLON.Action));
  52686. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52687. })(BABYLON || (BABYLON = {}));
  52688. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52689. var BABYLON;
  52690. (function (BABYLON) {
  52691. var SwitchBooleanAction = /** @class */ (function (_super) {
  52692. __extends(SwitchBooleanAction, _super);
  52693. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52694. var _this = _super.call(this, triggerOptions, condition) || this;
  52695. _this.propertyPath = propertyPath;
  52696. _this._target = _this._effectiveTarget = target;
  52697. return _this;
  52698. }
  52699. SwitchBooleanAction.prototype._prepare = function () {
  52700. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52701. this._property = this._getProperty(this.propertyPath);
  52702. };
  52703. SwitchBooleanAction.prototype.execute = function () {
  52704. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52705. };
  52706. SwitchBooleanAction.prototype.serialize = function (parent) {
  52707. return _super.prototype._serialize.call(this, {
  52708. name: "SwitchBooleanAction",
  52709. properties: [
  52710. BABYLON.Action._GetTargetProperty(this._target),
  52711. { name: "propertyPath", value: this.propertyPath }
  52712. ]
  52713. }, parent);
  52714. };
  52715. return SwitchBooleanAction;
  52716. }(BABYLON.Action));
  52717. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52718. var SetStateAction = /** @class */ (function (_super) {
  52719. __extends(SetStateAction, _super);
  52720. function SetStateAction(triggerOptions, target, value, condition) {
  52721. var _this = _super.call(this, triggerOptions, condition) || this;
  52722. _this.value = value;
  52723. _this._target = target;
  52724. return _this;
  52725. }
  52726. SetStateAction.prototype.execute = function () {
  52727. this._target.state = this.value;
  52728. };
  52729. SetStateAction.prototype.serialize = function (parent) {
  52730. return _super.prototype._serialize.call(this, {
  52731. name: "SetStateAction",
  52732. properties: [
  52733. BABYLON.Action._GetTargetProperty(this._target),
  52734. { name: "value", value: this.value }
  52735. ]
  52736. }, parent);
  52737. };
  52738. return SetStateAction;
  52739. }(BABYLON.Action));
  52740. BABYLON.SetStateAction = SetStateAction;
  52741. var SetValueAction = /** @class */ (function (_super) {
  52742. __extends(SetValueAction, _super);
  52743. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52744. var _this = _super.call(this, triggerOptions, condition) || this;
  52745. _this.propertyPath = propertyPath;
  52746. _this.value = value;
  52747. _this._target = _this._effectiveTarget = target;
  52748. return _this;
  52749. }
  52750. SetValueAction.prototype._prepare = function () {
  52751. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52752. this._property = this._getProperty(this.propertyPath);
  52753. };
  52754. SetValueAction.prototype.execute = function () {
  52755. this._effectiveTarget[this._property] = this.value;
  52756. if (this._target.markAsDirty) {
  52757. this._target.markAsDirty(this._property);
  52758. }
  52759. };
  52760. SetValueAction.prototype.serialize = function (parent) {
  52761. return _super.prototype._serialize.call(this, {
  52762. name: "SetValueAction",
  52763. properties: [
  52764. BABYLON.Action._GetTargetProperty(this._target),
  52765. { name: "propertyPath", value: this.propertyPath },
  52766. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52767. ]
  52768. }, parent);
  52769. };
  52770. return SetValueAction;
  52771. }(BABYLON.Action));
  52772. BABYLON.SetValueAction = SetValueAction;
  52773. var IncrementValueAction = /** @class */ (function (_super) {
  52774. __extends(IncrementValueAction, _super);
  52775. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52776. var _this = _super.call(this, triggerOptions, condition) || this;
  52777. _this.propertyPath = propertyPath;
  52778. _this.value = value;
  52779. _this._target = _this._effectiveTarget = target;
  52780. return _this;
  52781. }
  52782. IncrementValueAction.prototype._prepare = function () {
  52783. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52784. this._property = this._getProperty(this.propertyPath);
  52785. if (typeof this._effectiveTarget[this._property] !== "number") {
  52786. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52787. }
  52788. };
  52789. IncrementValueAction.prototype.execute = function () {
  52790. this._effectiveTarget[this._property] += this.value;
  52791. if (this._target.markAsDirty) {
  52792. this._target.markAsDirty(this._property);
  52793. }
  52794. };
  52795. IncrementValueAction.prototype.serialize = function (parent) {
  52796. return _super.prototype._serialize.call(this, {
  52797. name: "IncrementValueAction",
  52798. properties: [
  52799. BABYLON.Action._GetTargetProperty(this._target),
  52800. { name: "propertyPath", value: this.propertyPath },
  52801. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52802. ]
  52803. }, parent);
  52804. };
  52805. return IncrementValueAction;
  52806. }(BABYLON.Action));
  52807. BABYLON.IncrementValueAction = IncrementValueAction;
  52808. var PlayAnimationAction = /** @class */ (function (_super) {
  52809. __extends(PlayAnimationAction, _super);
  52810. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52811. var _this = _super.call(this, triggerOptions, condition) || this;
  52812. _this.from = from;
  52813. _this.to = to;
  52814. _this.loop = loop;
  52815. _this._target = target;
  52816. return _this;
  52817. }
  52818. PlayAnimationAction.prototype._prepare = function () {
  52819. };
  52820. PlayAnimationAction.prototype.execute = function () {
  52821. var scene = this._actionManager.getScene();
  52822. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52823. };
  52824. PlayAnimationAction.prototype.serialize = function (parent) {
  52825. return _super.prototype._serialize.call(this, {
  52826. name: "PlayAnimationAction",
  52827. properties: [
  52828. BABYLON.Action._GetTargetProperty(this._target),
  52829. { name: "from", value: String(this.from) },
  52830. { name: "to", value: String(this.to) },
  52831. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52832. ]
  52833. }, parent);
  52834. };
  52835. return PlayAnimationAction;
  52836. }(BABYLON.Action));
  52837. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52838. var StopAnimationAction = /** @class */ (function (_super) {
  52839. __extends(StopAnimationAction, _super);
  52840. function StopAnimationAction(triggerOptions, target, condition) {
  52841. var _this = _super.call(this, triggerOptions, condition) || this;
  52842. _this._target = target;
  52843. return _this;
  52844. }
  52845. StopAnimationAction.prototype._prepare = function () {
  52846. };
  52847. StopAnimationAction.prototype.execute = function () {
  52848. var scene = this._actionManager.getScene();
  52849. scene.stopAnimation(this._target);
  52850. };
  52851. StopAnimationAction.prototype.serialize = function (parent) {
  52852. return _super.prototype._serialize.call(this, {
  52853. name: "StopAnimationAction",
  52854. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52855. }, parent);
  52856. };
  52857. return StopAnimationAction;
  52858. }(BABYLON.Action));
  52859. BABYLON.StopAnimationAction = StopAnimationAction;
  52860. var DoNothingAction = /** @class */ (function (_super) {
  52861. __extends(DoNothingAction, _super);
  52862. function DoNothingAction(triggerOptions, condition) {
  52863. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52864. return _super.call(this, triggerOptions, condition) || this;
  52865. }
  52866. DoNothingAction.prototype.execute = function () {
  52867. };
  52868. DoNothingAction.prototype.serialize = function (parent) {
  52869. return _super.prototype._serialize.call(this, {
  52870. name: "DoNothingAction",
  52871. properties: []
  52872. }, parent);
  52873. };
  52874. return DoNothingAction;
  52875. }(BABYLON.Action));
  52876. BABYLON.DoNothingAction = DoNothingAction;
  52877. var CombineAction = /** @class */ (function (_super) {
  52878. __extends(CombineAction, _super);
  52879. function CombineAction(triggerOptions, children, condition) {
  52880. var _this = _super.call(this, triggerOptions, condition) || this;
  52881. _this.children = children;
  52882. return _this;
  52883. }
  52884. CombineAction.prototype._prepare = function () {
  52885. for (var index = 0; index < this.children.length; index++) {
  52886. this.children[index]._actionManager = this._actionManager;
  52887. this.children[index]._prepare();
  52888. }
  52889. };
  52890. CombineAction.prototype.execute = function (evt) {
  52891. for (var index = 0; index < this.children.length; index++) {
  52892. this.children[index].execute(evt);
  52893. }
  52894. };
  52895. CombineAction.prototype.serialize = function (parent) {
  52896. var serializationObject = _super.prototype._serialize.call(this, {
  52897. name: "CombineAction",
  52898. properties: [],
  52899. combine: []
  52900. }, parent);
  52901. for (var i = 0; i < this.children.length; i++) {
  52902. serializationObject.combine.push(this.children[i].serialize(null));
  52903. }
  52904. return serializationObject;
  52905. };
  52906. return CombineAction;
  52907. }(BABYLON.Action));
  52908. BABYLON.CombineAction = CombineAction;
  52909. var ExecuteCodeAction = /** @class */ (function (_super) {
  52910. __extends(ExecuteCodeAction, _super);
  52911. function ExecuteCodeAction(triggerOptions, func, condition) {
  52912. var _this = _super.call(this, triggerOptions, condition) || this;
  52913. _this.func = func;
  52914. return _this;
  52915. }
  52916. ExecuteCodeAction.prototype.execute = function (evt) {
  52917. this.func(evt);
  52918. };
  52919. return ExecuteCodeAction;
  52920. }(BABYLON.Action));
  52921. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52922. var SetParentAction = /** @class */ (function (_super) {
  52923. __extends(SetParentAction, _super);
  52924. function SetParentAction(triggerOptions, target, parent, condition) {
  52925. var _this = _super.call(this, triggerOptions, condition) || this;
  52926. _this._target = target;
  52927. _this._parent = parent;
  52928. return _this;
  52929. }
  52930. SetParentAction.prototype._prepare = function () {
  52931. };
  52932. SetParentAction.prototype.execute = function () {
  52933. if (this._target.parent === this._parent) {
  52934. return;
  52935. }
  52936. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52937. invertParentWorldMatrix.invert();
  52938. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52939. this._target.parent = this._parent;
  52940. };
  52941. SetParentAction.prototype.serialize = function (parent) {
  52942. return _super.prototype._serialize.call(this, {
  52943. name: "SetParentAction",
  52944. properties: [
  52945. BABYLON.Action._GetTargetProperty(this._target),
  52946. BABYLON.Action._GetTargetProperty(this._parent),
  52947. ]
  52948. }, parent);
  52949. };
  52950. return SetParentAction;
  52951. }(BABYLON.Action));
  52952. BABYLON.SetParentAction = SetParentAction;
  52953. var PlaySoundAction = /** @class */ (function (_super) {
  52954. __extends(PlaySoundAction, _super);
  52955. function PlaySoundAction(triggerOptions, sound, condition) {
  52956. var _this = _super.call(this, triggerOptions, condition) || this;
  52957. _this._sound = sound;
  52958. return _this;
  52959. }
  52960. PlaySoundAction.prototype._prepare = function () {
  52961. };
  52962. PlaySoundAction.prototype.execute = function () {
  52963. if (this._sound !== undefined)
  52964. this._sound.play();
  52965. };
  52966. PlaySoundAction.prototype.serialize = function (parent) {
  52967. return _super.prototype._serialize.call(this, {
  52968. name: "PlaySoundAction",
  52969. properties: [{ name: "sound", value: this._sound.name }]
  52970. }, parent);
  52971. };
  52972. return PlaySoundAction;
  52973. }(BABYLON.Action));
  52974. BABYLON.PlaySoundAction = PlaySoundAction;
  52975. var StopSoundAction = /** @class */ (function (_super) {
  52976. __extends(StopSoundAction, _super);
  52977. function StopSoundAction(triggerOptions, sound, condition) {
  52978. var _this = _super.call(this, triggerOptions, condition) || this;
  52979. _this._sound = sound;
  52980. return _this;
  52981. }
  52982. StopSoundAction.prototype._prepare = function () {
  52983. };
  52984. StopSoundAction.prototype.execute = function () {
  52985. if (this._sound !== undefined)
  52986. this._sound.stop();
  52987. };
  52988. StopSoundAction.prototype.serialize = function (parent) {
  52989. return _super.prototype._serialize.call(this, {
  52990. name: "StopSoundAction",
  52991. properties: [{ name: "sound", value: this._sound.name }]
  52992. }, parent);
  52993. };
  52994. return StopSoundAction;
  52995. }(BABYLON.Action));
  52996. BABYLON.StopSoundAction = StopSoundAction;
  52997. })(BABYLON || (BABYLON = {}));
  52998. //# sourceMappingURL=babylon.directActions.js.map
  52999. var BABYLON;
  53000. (function (BABYLON) {
  53001. var SpriteManager = /** @class */ (function () {
  53002. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53003. if (epsilon === void 0) { epsilon = 0.01; }
  53004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53005. this.name = name;
  53006. this.sprites = new Array();
  53007. this.renderingGroupId = 0;
  53008. this.layerMask = 0x0FFFFFFF;
  53009. this.fogEnabled = true;
  53010. this.isPickable = false;
  53011. /**
  53012. * An event triggered when the manager is disposed.
  53013. */
  53014. this.onDisposeObservable = new BABYLON.Observable();
  53015. this._vertexBuffers = {};
  53016. this._capacity = capacity;
  53017. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53018. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53019. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53020. if (cellSize.width && cellSize.height) {
  53021. this.cellWidth = cellSize.width;
  53022. this.cellHeight = cellSize.height;
  53023. }
  53024. else if (cellSize !== undefined) {
  53025. this.cellWidth = cellSize;
  53026. this.cellHeight = cellSize;
  53027. }
  53028. else {
  53029. return;
  53030. }
  53031. this._epsilon = epsilon;
  53032. this._scene = scene;
  53033. this._scene.spriteManagers.push(this);
  53034. var indices = [];
  53035. var index = 0;
  53036. for (var count = 0; count < capacity; count++) {
  53037. indices.push(index);
  53038. indices.push(index + 1);
  53039. indices.push(index + 2);
  53040. indices.push(index);
  53041. indices.push(index + 2);
  53042. indices.push(index + 3);
  53043. index += 4;
  53044. }
  53045. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53046. // VBO
  53047. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53048. this._vertexData = new Float32Array(capacity * 16 * 4);
  53049. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53050. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53051. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53052. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53053. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53054. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53055. this._vertexBuffers["options"] = options;
  53056. this._vertexBuffers["cellInfo"] = cellInfo;
  53057. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53058. // Effects
  53059. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53060. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53061. }
  53062. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53063. set: function (callback) {
  53064. if (this._onDisposeObserver) {
  53065. this.onDisposeObservable.remove(this._onDisposeObserver);
  53066. }
  53067. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(SpriteManager.prototype, "texture", {
  53073. get: function () {
  53074. return this._spriteTexture;
  53075. },
  53076. set: function (value) {
  53077. this._spriteTexture = value;
  53078. },
  53079. enumerable: true,
  53080. configurable: true
  53081. });
  53082. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53083. var arrayOffset = index * 16;
  53084. if (offsetX === 0)
  53085. offsetX = this._epsilon;
  53086. else if (offsetX === 1)
  53087. offsetX = 1 - this._epsilon;
  53088. if (offsetY === 0)
  53089. offsetY = this._epsilon;
  53090. else if (offsetY === 1)
  53091. offsetY = 1 - this._epsilon;
  53092. this._vertexData[arrayOffset] = sprite.position.x;
  53093. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53094. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53095. this._vertexData[arrayOffset + 3] = sprite.angle;
  53096. this._vertexData[arrayOffset + 4] = sprite.width;
  53097. this._vertexData[arrayOffset + 5] = sprite.height;
  53098. this._vertexData[arrayOffset + 6] = offsetX;
  53099. this._vertexData[arrayOffset + 7] = offsetY;
  53100. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53101. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53102. var offset = (sprite.cellIndex / rowSize) >> 0;
  53103. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53104. this._vertexData[arrayOffset + 11] = offset;
  53105. // Color
  53106. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53107. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53108. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53109. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53110. };
  53111. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53112. var count = Math.min(this._capacity, this.sprites.length);
  53113. var min = BABYLON.Vector3.Zero();
  53114. var max = BABYLON.Vector3.Zero();
  53115. var distance = Number.MAX_VALUE;
  53116. var currentSprite = null;
  53117. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53118. var cameraView = camera.getViewMatrix();
  53119. for (var index = 0; index < count; index++) {
  53120. var sprite = this.sprites[index];
  53121. if (!sprite) {
  53122. continue;
  53123. }
  53124. if (predicate) {
  53125. if (!predicate(sprite)) {
  53126. continue;
  53127. }
  53128. }
  53129. else if (!sprite.isPickable) {
  53130. continue;
  53131. }
  53132. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53133. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53134. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53135. if (ray.intersectsBoxMinMax(min, max)) {
  53136. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53137. if (distance > currentDistance) {
  53138. distance = currentDistance;
  53139. currentSprite = sprite;
  53140. if (fastCheck) {
  53141. break;
  53142. }
  53143. }
  53144. }
  53145. }
  53146. if (currentSprite) {
  53147. var result = new BABYLON.PickingInfo();
  53148. result.hit = true;
  53149. result.pickedSprite = currentSprite;
  53150. result.distance = distance;
  53151. return result;
  53152. }
  53153. return null;
  53154. };
  53155. SpriteManager.prototype.render = function () {
  53156. // Check
  53157. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53158. return;
  53159. var engine = this._scene.getEngine();
  53160. var baseSize = this._spriteTexture.getBaseSize();
  53161. // Sprites
  53162. var deltaTime = engine.getDeltaTime();
  53163. var max = Math.min(this._capacity, this.sprites.length);
  53164. var rowSize = baseSize.width / this.cellWidth;
  53165. var offset = 0;
  53166. for (var index = 0; index < max; index++) {
  53167. var sprite = this.sprites[index];
  53168. if (!sprite || !sprite.isVisible) {
  53169. continue;
  53170. }
  53171. sprite._animate(deltaTime);
  53172. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53173. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53174. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53175. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53176. }
  53177. this._buffer.update(this._vertexData);
  53178. // Render
  53179. var effect = this._effectBase;
  53180. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53181. effect = this._effectFog;
  53182. }
  53183. engine.enableEffect(effect);
  53184. var viewMatrix = this._scene.getViewMatrix();
  53185. effect.setTexture("diffuseSampler", this._spriteTexture);
  53186. effect.setMatrix("view", viewMatrix);
  53187. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53188. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53189. // Fog
  53190. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53191. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53192. effect.setColor3("vFogColor", this._scene.fogColor);
  53193. }
  53194. // VBOs
  53195. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53196. // Draw order
  53197. engine.setDepthFunctionToLessOrEqual();
  53198. effect.setBool("alphaTest", true);
  53199. engine.setColorWrite(false);
  53200. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53201. engine.setColorWrite(true);
  53202. effect.setBool("alphaTest", false);
  53203. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53204. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53206. };
  53207. SpriteManager.prototype.dispose = function () {
  53208. if (this._buffer) {
  53209. this._buffer.dispose();
  53210. this._buffer = null;
  53211. }
  53212. if (this._indexBuffer) {
  53213. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53214. this._indexBuffer = null;
  53215. }
  53216. if (this._spriteTexture) {
  53217. this._spriteTexture.dispose();
  53218. this._spriteTexture = null;
  53219. }
  53220. // Remove from scene
  53221. var index = this._scene.spriteManagers.indexOf(this);
  53222. this._scene.spriteManagers.splice(index, 1);
  53223. // Callback
  53224. this.onDisposeObservable.notifyObservers(this);
  53225. this.onDisposeObservable.clear();
  53226. };
  53227. return SpriteManager;
  53228. }());
  53229. BABYLON.SpriteManager = SpriteManager;
  53230. })(BABYLON || (BABYLON = {}));
  53231. //# sourceMappingURL=babylon.spriteManager.js.map
  53232. var BABYLON;
  53233. (function (BABYLON) {
  53234. var Sprite = /** @class */ (function () {
  53235. function Sprite(name, manager) {
  53236. this.name = name;
  53237. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53238. this.width = 1.0;
  53239. this.height = 1.0;
  53240. this.angle = 0;
  53241. this.cellIndex = 0;
  53242. this.invertU = 0;
  53243. this.invertV = 0;
  53244. this.animations = new Array();
  53245. this.isPickable = false;
  53246. this._animationStarted = false;
  53247. this._loopAnimation = false;
  53248. this._fromIndex = 0;
  53249. this._toIndex = 0;
  53250. this._delay = 0;
  53251. this._direction = 1;
  53252. this._time = 0;
  53253. /**
  53254. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53255. */
  53256. this.isVisible = true;
  53257. this._manager = manager;
  53258. this._manager.sprites.push(this);
  53259. this.position = BABYLON.Vector3.Zero();
  53260. }
  53261. Object.defineProperty(Sprite.prototype, "size", {
  53262. get: function () {
  53263. return this.width;
  53264. },
  53265. set: function (value) {
  53266. this.width = value;
  53267. this.height = value;
  53268. },
  53269. enumerable: true,
  53270. configurable: true
  53271. });
  53272. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53273. this._fromIndex = from;
  53274. this._toIndex = to;
  53275. this._loopAnimation = loop;
  53276. this._delay = delay;
  53277. this._animationStarted = true;
  53278. this._direction = from < to ? 1 : -1;
  53279. this.cellIndex = from;
  53280. this._time = 0;
  53281. this._onAnimationEnd = onAnimationEnd;
  53282. };
  53283. Sprite.prototype.stopAnimation = function () {
  53284. this._animationStarted = false;
  53285. };
  53286. Sprite.prototype._animate = function (deltaTime) {
  53287. if (!this._animationStarted)
  53288. return;
  53289. this._time += deltaTime;
  53290. if (this._time > this._delay) {
  53291. this._time = this._time % this._delay;
  53292. this.cellIndex += this._direction;
  53293. if (this.cellIndex > this._toIndex) {
  53294. if (this._loopAnimation) {
  53295. this.cellIndex = this._fromIndex;
  53296. }
  53297. else {
  53298. this.cellIndex = this._toIndex;
  53299. this._animationStarted = false;
  53300. if (this._onAnimationEnd) {
  53301. this._onAnimationEnd();
  53302. }
  53303. if (this.disposeWhenFinishedAnimating) {
  53304. this.dispose();
  53305. }
  53306. }
  53307. }
  53308. }
  53309. };
  53310. Sprite.prototype.dispose = function () {
  53311. for (var i = 0; i < this._manager.sprites.length; i++) {
  53312. if (this._manager.sprites[i] == this) {
  53313. this._manager.sprites.splice(i, 1);
  53314. }
  53315. }
  53316. };
  53317. return Sprite;
  53318. }());
  53319. BABYLON.Sprite = Sprite;
  53320. })(BABYLON || (BABYLON = {}));
  53321. //# sourceMappingURL=babylon.sprite.js.map
  53322. var BABYLON;
  53323. (function (BABYLON) {
  53324. var IntersectionInfo = /** @class */ (function () {
  53325. function IntersectionInfo(bu, bv, distance) {
  53326. this.bu = bu;
  53327. this.bv = bv;
  53328. this.distance = distance;
  53329. this.faceId = 0;
  53330. this.subMeshId = 0;
  53331. }
  53332. return IntersectionInfo;
  53333. }());
  53334. BABYLON.IntersectionInfo = IntersectionInfo;
  53335. /**
  53336. * Information about the result of picking within a scene
  53337. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53338. */
  53339. var PickingInfo = /** @class */ (function () {
  53340. function PickingInfo() {
  53341. /**
  53342. * If the pick collided with an object
  53343. */
  53344. this.hit = false;
  53345. /**
  53346. * Distance away where the pick collided
  53347. */
  53348. this.distance = 0;
  53349. /**
  53350. * The location of pick collision
  53351. */
  53352. this.pickedPoint = null;
  53353. /**
  53354. * The mesh corrisponding the the pick collision
  53355. */
  53356. this.pickedMesh = null;
  53357. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53358. this.bu = 0;
  53359. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53360. this.bv = 0;
  53361. /** The id of the face on the mesh that was picked */
  53362. this.faceId = -1;
  53363. /** Id of the the submesh that was picked */
  53364. this.subMeshId = 0;
  53365. /** If a sprite was picked, this will be the sprite the pick collided with */
  53366. this.pickedSprite = null;
  53367. /**
  53368. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53369. */
  53370. this.originMesh = null;
  53371. /**
  53372. * The ray that was used to perform the picking.
  53373. */
  53374. this.ray = null;
  53375. }
  53376. /**
  53377. * Gets the normal corrispodning to the face the pick collided with
  53378. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53379. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53380. * @returns The normal corrispodning to the face the pick collided with
  53381. */
  53382. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53383. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53384. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53385. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53386. return null;
  53387. }
  53388. var indices = this.pickedMesh.getIndices();
  53389. if (!indices) {
  53390. return null;
  53391. }
  53392. var result;
  53393. if (useVerticesNormals) {
  53394. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53395. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53396. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53397. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53398. normal0 = normal0.scale(this.bu);
  53399. normal1 = normal1.scale(this.bv);
  53400. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53401. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53402. }
  53403. else {
  53404. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53405. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53406. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53407. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53408. var p1p2 = vertex1.subtract(vertex2);
  53409. var p3p2 = vertex3.subtract(vertex2);
  53410. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53411. }
  53412. if (useWorldCoordinates) {
  53413. var wm = this.pickedMesh.getWorldMatrix();
  53414. if (this.pickedMesh.nonUniformScaling) {
  53415. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53416. wm = BABYLON.Tmp.Matrix[0];
  53417. wm.setTranslationFromFloats(0, 0, 0);
  53418. wm.invert();
  53419. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53420. wm = BABYLON.Tmp.Matrix[1];
  53421. }
  53422. result = BABYLON.Vector3.TransformNormal(result, wm);
  53423. }
  53424. result.normalize();
  53425. return result;
  53426. };
  53427. /**
  53428. * Gets the texture coordinates of where the pick occured
  53429. * @returns the vector containing the coordnates of the texture
  53430. */
  53431. PickingInfo.prototype.getTextureCoordinates = function () {
  53432. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53433. return null;
  53434. }
  53435. var indices = this.pickedMesh.getIndices();
  53436. if (!indices) {
  53437. return null;
  53438. }
  53439. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53440. if (!uvs) {
  53441. return null;
  53442. }
  53443. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53444. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53445. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53446. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53447. uv1 = uv1.scale(this.bu);
  53448. uv2 = uv2.scale(this.bv);
  53449. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53450. };
  53451. return PickingInfo;
  53452. }());
  53453. BABYLON.PickingInfo = PickingInfo;
  53454. })(BABYLON || (BABYLON = {}));
  53455. //# sourceMappingURL=babylon.pickingInfo.js.map
  53456. var BABYLON;
  53457. (function (BABYLON) {
  53458. var Ray = /** @class */ (function () {
  53459. function Ray(origin, direction, length) {
  53460. if (length === void 0) { length = Number.MAX_VALUE; }
  53461. this.origin = origin;
  53462. this.direction = direction;
  53463. this.length = length;
  53464. }
  53465. // Methods
  53466. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53467. var d = 0.0;
  53468. var maxValue = Number.MAX_VALUE;
  53469. var inv;
  53470. var min;
  53471. var max;
  53472. var temp;
  53473. if (Math.abs(this.direction.x) < 0.0000001) {
  53474. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53475. return false;
  53476. }
  53477. }
  53478. else {
  53479. inv = 1.0 / this.direction.x;
  53480. min = (minimum.x - this.origin.x) * inv;
  53481. max = (maximum.x - this.origin.x) * inv;
  53482. if (max === -Infinity) {
  53483. max = Infinity;
  53484. }
  53485. if (min > max) {
  53486. temp = min;
  53487. min = max;
  53488. max = temp;
  53489. }
  53490. d = Math.max(min, d);
  53491. maxValue = Math.min(max, maxValue);
  53492. if (d > maxValue) {
  53493. return false;
  53494. }
  53495. }
  53496. if (Math.abs(this.direction.y) < 0.0000001) {
  53497. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53498. return false;
  53499. }
  53500. }
  53501. else {
  53502. inv = 1.0 / this.direction.y;
  53503. min = (minimum.y - this.origin.y) * inv;
  53504. max = (maximum.y - this.origin.y) * inv;
  53505. if (max === -Infinity) {
  53506. max = Infinity;
  53507. }
  53508. if (min > max) {
  53509. temp = min;
  53510. min = max;
  53511. max = temp;
  53512. }
  53513. d = Math.max(min, d);
  53514. maxValue = Math.min(max, maxValue);
  53515. if (d > maxValue) {
  53516. return false;
  53517. }
  53518. }
  53519. if (Math.abs(this.direction.z) < 0.0000001) {
  53520. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53521. return false;
  53522. }
  53523. }
  53524. else {
  53525. inv = 1.0 / this.direction.z;
  53526. min = (minimum.z - this.origin.z) * inv;
  53527. max = (maximum.z - this.origin.z) * inv;
  53528. if (max === -Infinity) {
  53529. max = Infinity;
  53530. }
  53531. if (min > max) {
  53532. temp = min;
  53533. min = max;
  53534. max = temp;
  53535. }
  53536. d = Math.max(min, d);
  53537. maxValue = Math.min(max, maxValue);
  53538. if (d > maxValue) {
  53539. return false;
  53540. }
  53541. }
  53542. return true;
  53543. };
  53544. Ray.prototype.intersectsBox = function (box) {
  53545. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53546. };
  53547. Ray.prototype.intersectsSphere = function (sphere) {
  53548. var x = sphere.center.x - this.origin.x;
  53549. var y = sphere.center.y - this.origin.y;
  53550. var z = sphere.center.z - this.origin.z;
  53551. var pyth = (x * x) + (y * y) + (z * z);
  53552. var rr = sphere.radius * sphere.radius;
  53553. if (pyth <= rr) {
  53554. return true;
  53555. }
  53556. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53557. if (dot < 0.0) {
  53558. return false;
  53559. }
  53560. var temp = pyth - (dot * dot);
  53561. return temp <= rr;
  53562. };
  53563. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53564. if (!this._edge1) {
  53565. this._edge1 = BABYLON.Vector3.Zero();
  53566. this._edge2 = BABYLON.Vector3.Zero();
  53567. this._pvec = BABYLON.Vector3.Zero();
  53568. this._tvec = BABYLON.Vector3.Zero();
  53569. this._qvec = BABYLON.Vector3.Zero();
  53570. }
  53571. vertex1.subtractToRef(vertex0, this._edge1);
  53572. vertex2.subtractToRef(vertex0, this._edge2);
  53573. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53574. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53575. if (det === 0) {
  53576. return null;
  53577. }
  53578. var invdet = 1 / det;
  53579. this.origin.subtractToRef(vertex0, this._tvec);
  53580. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53581. if (bu < 0 || bu > 1.0) {
  53582. return null;
  53583. }
  53584. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53585. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53586. if (bv < 0 || bu + bv > 1.0) {
  53587. return null;
  53588. }
  53589. //check if the distance is longer than the predefined length.
  53590. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53591. if (distance > this.length) {
  53592. return null;
  53593. }
  53594. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53595. };
  53596. Ray.prototype.intersectsPlane = function (plane) {
  53597. var distance;
  53598. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53599. if (Math.abs(result1) < 9.99999997475243E-07) {
  53600. return null;
  53601. }
  53602. else {
  53603. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53604. distance = (-plane.d - result2) / result1;
  53605. if (distance < 0.0) {
  53606. if (distance < -9.99999997475243E-07) {
  53607. return null;
  53608. }
  53609. else {
  53610. return 0;
  53611. }
  53612. }
  53613. return distance;
  53614. }
  53615. };
  53616. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53617. var tm = BABYLON.Tmp.Matrix[0];
  53618. mesh.getWorldMatrix().invertToRef(tm);
  53619. if (this._tmpRay) {
  53620. Ray.TransformToRef(this, tm, this._tmpRay);
  53621. }
  53622. else {
  53623. this._tmpRay = Ray.Transform(this, tm);
  53624. }
  53625. return mesh.intersects(this._tmpRay, fastCheck);
  53626. };
  53627. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53628. if (results) {
  53629. results.length = 0;
  53630. }
  53631. else {
  53632. results = [];
  53633. }
  53634. for (var i = 0; i < meshes.length; i++) {
  53635. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53636. if (pickInfo.hit) {
  53637. results.push(pickInfo);
  53638. }
  53639. }
  53640. results.sort(this._comparePickingInfo);
  53641. return results;
  53642. };
  53643. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53644. if (pickingInfoA.distance < pickingInfoB.distance) {
  53645. return -1;
  53646. }
  53647. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53648. return 1;
  53649. }
  53650. else {
  53651. return 0;
  53652. }
  53653. };
  53654. /**
  53655. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53656. * @param sega the first point of the segment to test the intersection against
  53657. * @param segb the second point of the segment to test the intersection against
  53658. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53659. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53660. */
  53661. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53662. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53663. var u = segb.subtract(sega);
  53664. var v = rsegb.subtract(this.origin);
  53665. var w = sega.subtract(this.origin);
  53666. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53667. var b = BABYLON.Vector3.Dot(u, v);
  53668. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53669. var d = BABYLON.Vector3.Dot(u, w);
  53670. var e = BABYLON.Vector3.Dot(v, w);
  53671. var D = a * c - b * b; // always >= 0
  53672. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53673. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53674. // compute the line parameters of the two closest points
  53675. if (D < Ray.smallnum) { // the lines are almost parallel
  53676. sN = 0.0; // force using point P0 on segment S1
  53677. sD = 1.0; // to prevent possible division by 0.0 later
  53678. tN = e;
  53679. tD = c;
  53680. }
  53681. else { // get the closest points on the infinite lines
  53682. sN = (b * e - c * d);
  53683. tN = (a * e - b * d);
  53684. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53685. sN = 0.0;
  53686. tN = e;
  53687. tD = c;
  53688. }
  53689. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53690. sN = sD;
  53691. tN = e + b;
  53692. tD = c;
  53693. }
  53694. }
  53695. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53696. tN = 0.0;
  53697. // recompute sc for this edge
  53698. if (-d < 0.0) {
  53699. sN = 0.0;
  53700. }
  53701. else if (-d > a)
  53702. sN = sD;
  53703. else {
  53704. sN = -d;
  53705. sD = a;
  53706. }
  53707. }
  53708. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53709. tN = tD;
  53710. // recompute sc for this edge
  53711. if ((-d + b) < 0.0) {
  53712. sN = 0;
  53713. }
  53714. else if ((-d + b) > a) {
  53715. sN = sD;
  53716. }
  53717. else {
  53718. sN = (-d + b);
  53719. sD = a;
  53720. }
  53721. }
  53722. // finally do the division to get sc and tc
  53723. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53724. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53725. // get the difference of the two closest points
  53726. var qtc = v.multiplyByFloats(tc, tc, tc);
  53727. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53728. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53729. if (isIntersected) {
  53730. return qtc.length();
  53731. }
  53732. return -1;
  53733. };
  53734. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53735. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53736. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53737. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53738. this.direction.normalize();
  53739. return this;
  53740. };
  53741. // Statics
  53742. Ray.Zero = function () {
  53743. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53744. };
  53745. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53746. var result = Ray.Zero();
  53747. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53748. };
  53749. /**
  53750. * 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
  53751. * transformed to the given world matrix.
  53752. * @param origin The origin point
  53753. * @param end The end point
  53754. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53755. */
  53756. Ray.CreateNewFromTo = function (origin, end, world) {
  53757. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53758. var direction = end.subtract(origin);
  53759. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53760. direction.normalize();
  53761. return Ray.Transform(new Ray(origin, direction, length), world);
  53762. };
  53763. Ray.Transform = function (ray, matrix) {
  53764. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53765. Ray.TransformToRef(ray, matrix, result);
  53766. return result;
  53767. };
  53768. Ray.TransformToRef = function (ray, matrix, result) {
  53769. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53770. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53771. result.length = ray.length;
  53772. var dir = result.direction;
  53773. var len = dir.length();
  53774. if (!(len === 0 || len === 1)) {
  53775. var num = 1.0 / len;
  53776. dir.x *= num;
  53777. dir.y *= num;
  53778. dir.z *= num;
  53779. result.length *= len;
  53780. }
  53781. };
  53782. Ray.smallnum = 0.00000001;
  53783. Ray.rayl = 10e8;
  53784. return Ray;
  53785. }());
  53786. BABYLON.Ray = Ray;
  53787. })(BABYLON || (BABYLON = {}));
  53788. //# sourceMappingURL=babylon.ray.js.map
  53789. var BABYLON;
  53790. (function (BABYLON) {
  53791. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53792. if (boxMin.x > sphereCenter.x + sphereRadius)
  53793. return false;
  53794. if (sphereCenter.x - sphereRadius > boxMax.x)
  53795. return false;
  53796. if (boxMin.y > sphereCenter.y + sphereRadius)
  53797. return false;
  53798. if (sphereCenter.y - sphereRadius > boxMax.y)
  53799. return false;
  53800. if (boxMin.z > sphereCenter.z + sphereRadius)
  53801. return false;
  53802. if (sphereCenter.z - sphereRadius > boxMax.z)
  53803. return false;
  53804. return true;
  53805. };
  53806. var getLowestRoot = (function () {
  53807. var result = { root: 0, found: false };
  53808. return function (a, b, c, maxR) {
  53809. result.root = 0;
  53810. result.found = false;
  53811. var determinant = b * b - 4.0 * a * c;
  53812. if (determinant < 0)
  53813. return result;
  53814. var sqrtD = Math.sqrt(determinant);
  53815. var r1 = (-b - sqrtD) / (2.0 * a);
  53816. var r2 = (-b + sqrtD) / (2.0 * a);
  53817. if (r1 > r2) {
  53818. var temp = r2;
  53819. r2 = r1;
  53820. r1 = temp;
  53821. }
  53822. if (r1 > 0 && r1 < maxR) {
  53823. result.root = r1;
  53824. result.found = true;
  53825. return result;
  53826. }
  53827. if (r2 > 0 && r2 < maxR) {
  53828. result.root = r2;
  53829. result.found = true;
  53830. return result;
  53831. }
  53832. return result;
  53833. };
  53834. })();
  53835. var Collider = /** @class */ (function () {
  53836. function Collider() {
  53837. this._collisionPoint = BABYLON.Vector3.Zero();
  53838. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53839. this._tempVector = BABYLON.Vector3.Zero();
  53840. this._tempVector2 = BABYLON.Vector3.Zero();
  53841. this._tempVector3 = BABYLON.Vector3.Zero();
  53842. this._tempVector4 = BABYLON.Vector3.Zero();
  53843. this._edge = BABYLON.Vector3.Zero();
  53844. this._baseToVertex = BABYLON.Vector3.Zero();
  53845. this._destinationPoint = BABYLON.Vector3.Zero();
  53846. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53847. this._displacementVector = BABYLON.Vector3.Zero();
  53848. this._radius = BABYLON.Vector3.One();
  53849. this._retry = 0;
  53850. this._basePointWorld = BABYLON.Vector3.Zero();
  53851. this._velocityWorld = BABYLON.Vector3.Zero();
  53852. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53853. this._collisionMask = -1;
  53854. }
  53855. Object.defineProperty(Collider.prototype, "collisionMask", {
  53856. get: function () {
  53857. return this._collisionMask;
  53858. },
  53859. set: function (mask) {
  53860. this._collisionMask = !isNaN(mask) ? mask : -1;
  53861. },
  53862. enumerable: true,
  53863. configurable: true
  53864. });
  53865. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53866. /**
  53867. * Gets the plane normal used to compute the sliding response (in local space)
  53868. */
  53869. get: function () {
  53870. return this._slidePlaneNormal;
  53871. },
  53872. enumerable: true,
  53873. configurable: true
  53874. });
  53875. // Methods
  53876. Collider.prototype._initialize = function (source, dir, e) {
  53877. this._velocity = dir;
  53878. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53879. this._basePoint = source;
  53880. source.multiplyToRef(this._radius, this._basePointWorld);
  53881. dir.multiplyToRef(this._radius, this._velocityWorld);
  53882. this._velocityWorldLength = this._velocityWorld.length();
  53883. this._epsilon = e;
  53884. this.collisionFound = false;
  53885. };
  53886. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53887. pa.subtractToRef(point, this._tempVector);
  53888. pb.subtractToRef(point, this._tempVector2);
  53889. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53890. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53891. if (d < 0)
  53892. return false;
  53893. pc.subtractToRef(point, this._tempVector3);
  53894. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53895. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53896. if (d < 0)
  53897. return false;
  53898. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53899. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53900. return d >= 0;
  53901. };
  53902. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53903. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53904. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53905. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53906. return false;
  53907. }
  53908. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53909. return false;
  53910. return true;
  53911. };
  53912. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53913. var t0;
  53914. var embeddedInPlane = false;
  53915. //defensive programming, actually not needed.
  53916. if (!trianglePlaneArray) {
  53917. trianglePlaneArray = [];
  53918. }
  53919. if (!trianglePlaneArray[faceIndex]) {
  53920. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53921. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53922. }
  53923. var trianglePlane = trianglePlaneArray[faceIndex];
  53924. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53925. return;
  53926. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53927. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53928. if (normalDotVelocity == 0) {
  53929. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53930. return;
  53931. embeddedInPlane = true;
  53932. t0 = 0;
  53933. }
  53934. else {
  53935. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53936. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53937. if (t0 > t1) {
  53938. var temp = t1;
  53939. t1 = t0;
  53940. t0 = temp;
  53941. }
  53942. if (t0 > 1.0 || t1 < 0.0)
  53943. return;
  53944. if (t0 < 0)
  53945. t0 = 0;
  53946. if (t0 > 1.0)
  53947. t0 = 1.0;
  53948. }
  53949. this._collisionPoint.copyFromFloats(0, 0, 0);
  53950. var found = false;
  53951. var t = 1.0;
  53952. if (!embeddedInPlane) {
  53953. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53954. this._velocity.scaleToRef(t0, this._tempVector);
  53955. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53956. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53957. found = true;
  53958. t = t0;
  53959. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53960. }
  53961. }
  53962. if (!found) {
  53963. var velocitySquaredLength = this._velocity.lengthSquared();
  53964. var a = velocitySquaredLength;
  53965. this._basePoint.subtractToRef(p1, this._tempVector);
  53966. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53967. var c = this._tempVector.lengthSquared() - 1.0;
  53968. var lowestRoot = getLowestRoot(a, b, c, t);
  53969. if (lowestRoot.found) {
  53970. t = lowestRoot.root;
  53971. found = true;
  53972. this._collisionPoint.copyFrom(p1);
  53973. }
  53974. this._basePoint.subtractToRef(p2, this._tempVector);
  53975. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53976. c = this._tempVector.lengthSquared() - 1.0;
  53977. lowestRoot = getLowestRoot(a, b, c, t);
  53978. if (lowestRoot.found) {
  53979. t = lowestRoot.root;
  53980. found = true;
  53981. this._collisionPoint.copyFrom(p2);
  53982. }
  53983. this._basePoint.subtractToRef(p3, this._tempVector);
  53984. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53985. c = this._tempVector.lengthSquared() - 1.0;
  53986. lowestRoot = getLowestRoot(a, b, c, t);
  53987. if (lowestRoot.found) {
  53988. t = lowestRoot.root;
  53989. found = true;
  53990. this._collisionPoint.copyFrom(p3);
  53991. }
  53992. p2.subtractToRef(p1, this._edge);
  53993. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53994. var edgeSquaredLength = this._edge.lengthSquared();
  53995. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53996. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53997. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53998. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53999. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54000. lowestRoot = getLowestRoot(a, b, c, t);
  54001. if (lowestRoot.found) {
  54002. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54003. if (f >= 0.0 && f <= 1.0) {
  54004. t = lowestRoot.root;
  54005. found = true;
  54006. this._edge.scaleInPlace(f);
  54007. p1.addToRef(this._edge, this._collisionPoint);
  54008. }
  54009. }
  54010. p3.subtractToRef(p2, this._edge);
  54011. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54012. edgeSquaredLength = this._edge.lengthSquared();
  54013. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54014. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54015. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54016. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54017. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54018. lowestRoot = getLowestRoot(a, b, c, t);
  54019. if (lowestRoot.found) {
  54020. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54021. if (f >= 0.0 && f <= 1.0) {
  54022. t = lowestRoot.root;
  54023. found = true;
  54024. this._edge.scaleInPlace(f);
  54025. p2.addToRef(this._edge, this._collisionPoint);
  54026. }
  54027. }
  54028. p1.subtractToRef(p3, this._edge);
  54029. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54030. edgeSquaredLength = this._edge.lengthSquared();
  54031. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54032. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54033. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54034. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54035. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54036. lowestRoot = getLowestRoot(a, b, c, t);
  54037. if (lowestRoot.found) {
  54038. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54039. if (f >= 0.0 && f <= 1.0) {
  54040. t = lowestRoot.root;
  54041. found = true;
  54042. this._edge.scaleInPlace(f);
  54043. p3.addToRef(this._edge, this._collisionPoint);
  54044. }
  54045. }
  54046. }
  54047. if (found) {
  54048. var distToCollision = t * this._velocity.length();
  54049. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54050. if (!this.intersectionPoint) {
  54051. this.intersectionPoint = this._collisionPoint.clone();
  54052. }
  54053. else {
  54054. this.intersectionPoint.copyFrom(this._collisionPoint);
  54055. }
  54056. this._nearestDistance = distToCollision;
  54057. this.collisionFound = true;
  54058. }
  54059. }
  54060. };
  54061. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54062. for (var i = indexStart; i < indexEnd; i += 3) {
  54063. var p1 = pts[indices[i] - decal];
  54064. var p2 = pts[indices[i + 1] - decal];
  54065. var p3 = pts[indices[i + 2] - decal];
  54066. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54067. }
  54068. };
  54069. Collider.prototype._getResponse = function (pos, vel) {
  54070. pos.addToRef(vel, this._destinationPoint);
  54071. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54072. this._basePoint.addToRef(vel, pos);
  54073. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54074. this._slidePlaneNormal.normalize();
  54075. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54076. pos.addInPlace(this._displacementVector);
  54077. this.intersectionPoint.addInPlace(this._displacementVector);
  54078. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54079. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54080. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54081. };
  54082. return Collider;
  54083. }());
  54084. BABYLON.Collider = Collider;
  54085. })(BABYLON || (BABYLON = {}));
  54086. //# sourceMappingURL=babylon.collider.js.map
  54087. var BABYLON;
  54088. (function (BABYLON) {
  54089. //WebWorker code will be inserted to this variable.
  54090. BABYLON.CollisionWorker = "";
  54091. /** Defines supported task for worker process */
  54092. var WorkerTaskType;
  54093. (function (WorkerTaskType) {
  54094. /** Initialization */
  54095. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54096. /** Update of geometry */
  54097. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54098. /** Evaluate collision */
  54099. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54100. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54101. /** Defines kind of replies returned by worker */
  54102. var WorkerReplyType;
  54103. (function (WorkerReplyType) {
  54104. /** Success */
  54105. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54106. /** Unkown error */
  54107. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54108. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54109. var CollisionCoordinatorWorker = /** @class */ (function () {
  54110. function CollisionCoordinatorWorker() {
  54111. var _this = this;
  54112. this._scaledPosition = BABYLON.Vector3.Zero();
  54113. this._scaledVelocity = BABYLON.Vector3.Zero();
  54114. this.onMeshUpdated = function (transformNode) {
  54115. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54116. };
  54117. this.onGeometryUpdated = function (geometry) {
  54118. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54119. };
  54120. this._afterRender = function () {
  54121. if (!_this._init)
  54122. return;
  54123. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54124. return;
  54125. }
  54126. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54127. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54128. if (_this._runningUpdated > 4) {
  54129. return;
  54130. }
  54131. ++_this._runningUpdated;
  54132. var payload = {
  54133. updatedMeshes: _this._addUpdateMeshesList,
  54134. updatedGeometries: _this._addUpdateGeometriesList,
  54135. removedGeometries: _this._toRemoveGeometryArray,
  54136. removedMeshes: _this._toRemoveMeshesArray
  54137. };
  54138. var message = {
  54139. payload: payload,
  54140. taskType: WorkerTaskType.UPDATE
  54141. };
  54142. var serializable = [];
  54143. for (var id in payload.updatedGeometries) {
  54144. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54145. //prepare transferables
  54146. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54147. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54148. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54149. }
  54150. }
  54151. _this._worker.postMessage(message, serializable);
  54152. _this._addUpdateMeshesList = {};
  54153. _this._addUpdateGeometriesList = {};
  54154. _this._toRemoveGeometryArray = [];
  54155. _this._toRemoveMeshesArray = [];
  54156. };
  54157. this._onMessageFromWorker = function (e) {
  54158. var returnData = e.data;
  54159. if (returnData.error != WorkerReplyType.SUCCESS) {
  54160. //TODO what errors can be returned from the worker?
  54161. BABYLON.Tools.Warn("error returned from worker!");
  54162. return;
  54163. }
  54164. switch (returnData.taskType) {
  54165. case WorkerTaskType.INIT:
  54166. _this._init = true;
  54167. //Update the worked with ALL of the scene's current state
  54168. _this._scene.meshes.forEach(function (mesh) {
  54169. _this.onMeshAdded(mesh);
  54170. });
  54171. _this._scene.getGeometries().forEach(function (geometry) {
  54172. _this.onGeometryAdded(geometry);
  54173. });
  54174. break;
  54175. case WorkerTaskType.UPDATE:
  54176. _this._runningUpdated--;
  54177. break;
  54178. case WorkerTaskType.COLLIDE:
  54179. var returnPayload = returnData.payload;
  54180. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54181. return;
  54182. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54183. if (callback) {
  54184. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54185. if (mesh) {
  54186. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54187. }
  54188. }
  54189. //cleanup
  54190. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54191. break;
  54192. }
  54193. };
  54194. this._collisionsCallbackArray = [];
  54195. this._init = false;
  54196. this._runningUpdated = 0;
  54197. this._addUpdateMeshesList = {};
  54198. this._addUpdateGeometriesList = {};
  54199. this._toRemoveGeometryArray = [];
  54200. this._toRemoveMeshesArray = [];
  54201. }
  54202. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54203. if (!this._init)
  54204. return;
  54205. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54206. return;
  54207. position.divideToRef(collider._radius, this._scaledPosition);
  54208. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54209. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54210. var payload = {
  54211. collider: {
  54212. position: this._scaledPosition.asArray(),
  54213. velocity: this._scaledVelocity.asArray(),
  54214. radius: collider._radius.asArray()
  54215. },
  54216. collisionId: collisionIndex,
  54217. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54218. maximumRetry: maximumRetry
  54219. };
  54220. var message = {
  54221. payload: payload,
  54222. taskType: WorkerTaskType.COLLIDE
  54223. };
  54224. this._worker.postMessage(message);
  54225. };
  54226. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54227. this._scene = scene;
  54228. this._scene.registerAfterRender(this._afterRender);
  54229. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54230. this._worker = new Worker(workerUrl);
  54231. this._worker.onmessage = this._onMessageFromWorker;
  54232. var message = {
  54233. payload: {},
  54234. taskType: WorkerTaskType.INIT
  54235. };
  54236. this._worker.postMessage(message);
  54237. };
  54238. CollisionCoordinatorWorker.prototype.destroy = function () {
  54239. this._scene.unregisterAfterRender(this._afterRender);
  54240. this._worker.terminate();
  54241. };
  54242. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54243. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54244. this.onMeshUpdated(mesh);
  54245. };
  54246. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54247. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54248. };
  54249. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54250. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54251. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54252. this.onGeometryUpdated(geometry);
  54253. };
  54254. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54255. this._toRemoveGeometryArray.push(geometry.id);
  54256. };
  54257. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54258. var submeshes = [];
  54259. if (mesh.subMeshes) {
  54260. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54261. var boundingInfo = sm.getBoundingInfo();
  54262. return {
  54263. position: idx,
  54264. verticesStart: sm.verticesStart,
  54265. verticesCount: sm.verticesCount,
  54266. indexStart: sm.indexStart,
  54267. indexCount: sm.indexCount,
  54268. hasMaterial: !!sm.getMaterial(),
  54269. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54270. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54271. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54272. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54273. };
  54274. });
  54275. }
  54276. var geometryId = null;
  54277. if (mesh instanceof BABYLON.Mesh) {
  54278. var geometry = mesh.geometry;
  54279. geometryId = geometry ? geometry.id : null;
  54280. }
  54281. else if (mesh instanceof BABYLON.InstancedMesh) {
  54282. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54283. geometryId = geometry ? geometry.id : null;
  54284. }
  54285. var boundingInfo = mesh.getBoundingInfo();
  54286. return {
  54287. uniqueId: mesh.uniqueId,
  54288. id: mesh.id,
  54289. name: mesh.name,
  54290. geometryId: geometryId,
  54291. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54292. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54293. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54294. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54295. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54296. subMeshes: submeshes,
  54297. checkCollisions: mesh.checkCollisions
  54298. };
  54299. };
  54300. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54301. return {
  54302. id: geometry.id,
  54303. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54304. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54305. indices: new Uint32Array(geometry.getIndices() || []),
  54306. };
  54307. };
  54308. return CollisionCoordinatorWorker;
  54309. }());
  54310. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54311. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54312. function CollisionCoordinatorLegacy() {
  54313. this._scaledPosition = BABYLON.Vector3.Zero();
  54314. this._scaledVelocity = BABYLON.Vector3.Zero();
  54315. this._finalPosition = BABYLON.Vector3.Zero();
  54316. }
  54317. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54318. position.divideToRef(collider._radius, this._scaledPosition);
  54319. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54320. collider.collidedMesh = null;
  54321. collider._retry = 0;
  54322. collider._initialVelocity = this._scaledVelocity;
  54323. collider._initialPosition = this._scaledPosition;
  54324. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54325. this._finalPosition.multiplyInPlace(collider._radius);
  54326. //run the callback
  54327. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54328. };
  54329. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54330. this._scene = scene;
  54331. };
  54332. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54333. //Legacy need no destruction method.
  54334. };
  54335. //No update in legacy mode
  54336. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54337. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54338. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54339. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54340. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54341. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54342. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54343. if (excludedMesh === void 0) { excludedMesh = null; }
  54344. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54345. if (collider._retry >= maximumRetry) {
  54346. finalPosition.copyFrom(position);
  54347. return;
  54348. }
  54349. // Check if this is a mesh else camera or -1
  54350. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54351. collider._initialize(position, velocity, closeDistance);
  54352. // Check all meshes
  54353. for (var index = 0; index < this._scene.meshes.length; index++) {
  54354. var mesh = this._scene.meshes[index];
  54355. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54356. mesh._checkCollision(collider);
  54357. }
  54358. }
  54359. if (!collider.collisionFound) {
  54360. position.addToRef(velocity, finalPosition);
  54361. return;
  54362. }
  54363. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54364. collider._getResponse(position, velocity);
  54365. }
  54366. if (velocity.length() <= closeDistance) {
  54367. finalPosition.copyFrom(position);
  54368. return;
  54369. }
  54370. collider._retry++;
  54371. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54372. };
  54373. return CollisionCoordinatorLegacy;
  54374. }());
  54375. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54376. })(BABYLON || (BABYLON = {}));
  54377. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54378. var BABYLON;
  54379. (function (BABYLON) {
  54380. /**
  54381. * A particle represents one of the element emitted by a particle system.
  54382. * This is mainly define by its coordinates, direction, velocity and age.
  54383. */
  54384. var Particle = /** @class */ (function () {
  54385. /**
  54386. * Creates a new instance Particle
  54387. * @param particleSystem the particle system the particle belongs to
  54388. */
  54389. function Particle(
  54390. /**
  54391. * particleSystem the particle system the particle belongs to.
  54392. */
  54393. particleSystem) {
  54394. this.particleSystem = particleSystem;
  54395. /**
  54396. * The world position of the particle in the scene.
  54397. */
  54398. this.position = BABYLON.Vector3.Zero();
  54399. /**
  54400. * The world direction of the particle in the scene.
  54401. */
  54402. this.direction = BABYLON.Vector3.Zero();
  54403. /**
  54404. * The color of the particle.
  54405. */
  54406. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54407. /**
  54408. * The color change of the particle per step.
  54409. */
  54410. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54411. /**
  54412. * Defines how long will the life of the particle be.
  54413. */
  54414. this.lifeTime = 1.0;
  54415. /**
  54416. * The current age of the particle.
  54417. */
  54418. this.age = 0;
  54419. /**
  54420. * The current size of the particle.
  54421. */
  54422. this.size = 0;
  54423. /**
  54424. * The current scale of the particle.
  54425. */
  54426. this.scale = new BABYLON.Vector2(1, 1);
  54427. /**
  54428. * The current angle of the particle.
  54429. */
  54430. this.angle = 0;
  54431. /**
  54432. * Defines how fast is the angle changing.
  54433. */
  54434. this.angularSpeed = 0;
  54435. /**
  54436. * Defines the cell index used by the particle to be rendered from a sprite.
  54437. */
  54438. this.cellIndex = 0;
  54439. /** @hidden */
  54440. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54441. /** @hidden */
  54442. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54443. /** @hidden */
  54444. this._currentSize1 = 0;
  54445. /** @hidden */
  54446. this._currentSize2 = 0;
  54447. /** @hidden */
  54448. this._currentAngularSpeed1 = 0;
  54449. /** @hidden */
  54450. this._currentAngularSpeed2 = 0;
  54451. /** @hidden */
  54452. this._currentVelocity1 = 0;
  54453. /** @hidden */
  54454. this._currentVelocity2 = 0;
  54455. if (!this.particleSystem.isAnimationSheetEnabled) {
  54456. return;
  54457. }
  54458. this.updateCellInfoFromSystem();
  54459. }
  54460. Particle.prototype.updateCellInfoFromSystem = function () {
  54461. this.cellIndex = this.particleSystem.startSpriteCellID;
  54462. };
  54463. /**
  54464. * Defines how the sprite cell index is updated for the particle
  54465. */
  54466. Particle.prototype.updateCellIndex = function () {
  54467. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54468. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54469. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54470. };
  54471. /**
  54472. * Copy the properties of particle to another one.
  54473. * @param other the particle to copy the information to.
  54474. */
  54475. Particle.prototype.copyTo = function (other) {
  54476. other.position.copyFrom(this.position);
  54477. if (this._initialDirection) {
  54478. if (other._initialDirection) {
  54479. other._initialDirection.copyFrom(this._initialDirection);
  54480. }
  54481. else {
  54482. other._initialDirection = this._initialDirection.clone();
  54483. }
  54484. }
  54485. else {
  54486. other._initialDirection = null;
  54487. }
  54488. other.direction.copyFrom(this.direction);
  54489. other.color.copyFrom(this.color);
  54490. other.colorStep.copyFrom(this.colorStep);
  54491. other.lifeTime = this.lifeTime;
  54492. other.age = this.age;
  54493. other.size = this.size;
  54494. other.scale.copyFrom(this.scale);
  54495. other.angle = this.angle;
  54496. other.angularSpeed = this.angularSpeed;
  54497. other.particleSystem = this.particleSystem;
  54498. other.cellIndex = this.cellIndex;
  54499. if (this._currentColorGradient) {
  54500. other._currentColorGradient = this._currentColorGradient;
  54501. other._currentColor1.copyFrom(this._currentColor1);
  54502. other._currentColor2.copyFrom(this._currentColor2);
  54503. }
  54504. if (this._currentSizeGradient) {
  54505. other._currentSizeGradient = this._currentSizeGradient;
  54506. other._currentSize1 = this._currentSize1;
  54507. other._currentSize2 = this._currentSize2;
  54508. }
  54509. if (this._currentAngularSpeedGradient) {
  54510. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54511. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54512. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54513. }
  54514. if (this._currentVelocityGradient) {
  54515. other._currentVelocityGradient = this._currentVelocityGradient;
  54516. other._currentVelocity1 = this._currentVelocity1;
  54517. other._currentVelocity2 = this._currentVelocity2;
  54518. }
  54519. if (this.particleSystem.isAnimationSheetEnabled) {
  54520. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54521. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54522. }
  54523. };
  54524. return Particle;
  54525. }());
  54526. BABYLON.Particle = Particle;
  54527. })(BABYLON || (BABYLON = {}));
  54528. //# sourceMappingURL=babylon.particle.js.map
  54529. var BABYLON;
  54530. (function (BABYLON) {
  54531. /**
  54532. * This represents a particle system in Babylon.
  54533. * 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.
  54534. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54535. * @example https://doc.babylonjs.com/babylon101/particles
  54536. */
  54537. var ParticleSystem = /** @class */ (function () {
  54538. /**
  54539. * Instantiates a particle system.
  54540. * 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.
  54541. * @param name The name of the particle system
  54542. * @param capacity The max number of particles alive at the same time
  54543. * @param scene The scene the particle system belongs to
  54544. * @param customEffect a custom effect used to change the way particles are rendered by default
  54545. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54546. * @param epsilon Offset used to render the particles
  54547. */
  54548. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54549. if (customEffect === void 0) { customEffect = null; }
  54550. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54551. if (epsilon === void 0) { epsilon = 0.01; }
  54552. var _this = this;
  54553. /**
  54554. * List of animations used by the particle system.
  54555. */
  54556. this.animations = [];
  54557. /**
  54558. * The rendering group used by the Particle system to chose when to render.
  54559. */
  54560. this.renderingGroupId = 0;
  54561. /**
  54562. * The emitter represents the Mesh or position we are attaching the particle system to.
  54563. */
  54564. this.emitter = null;
  54565. /**
  54566. * The maximum number of particles to emit per frame
  54567. */
  54568. this.emitRate = 10;
  54569. /**
  54570. * If you want to launch only a few particles at once, that can be done, as well.
  54571. */
  54572. this.manualEmitCount = -1;
  54573. /**
  54574. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54575. */
  54576. this.updateSpeed = 0.01;
  54577. /**
  54578. * The amount of time the particle system is running (depends of the overall update speed).
  54579. */
  54580. this.targetStopDuration = 0;
  54581. /**
  54582. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54583. */
  54584. this.disposeOnStop = false;
  54585. /**
  54586. * Minimum power of emitting particles.
  54587. */
  54588. this.minEmitPower = 1;
  54589. /**
  54590. * Maximum power of emitting particles.
  54591. */
  54592. this.maxEmitPower = 1;
  54593. /**
  54594. * Minimum life time of emitting particles.
  54595. */
  54596. this.minLifeTime = 1;
  54597. /**
  54598. * Maximum life time of emitting particles.
  54599. */
  54600. this.maxLifeTime = 1;
  54601. /**
  54602. * Minimum Size of emitting particles.
  54603. */
  54604. this.minSize = 1;
  54605. /**
  54606. * Maximum Size of emitting particles.
  54607. */
  54608. this.maxSize = 1;
  54609. /**
  54610. * Minimum scale of emitting particles on X axis.
  54611. */
  54612. this.minScaleX = 1;
  54613. /**
  54614. * Maximum scale of emitting particles on X axis.
  54615. */
  54616. this.maxScaleX = 1;
  54617. /**
  54618. * Minimum scale of emitting particles on Y axis.
  54619. */
  54620. this.minScaleY = 1;
  54621. /**
  54622. * Maximum scale of emitting particles on Y axis.
  54623. */
  54624. this.maxScaleY = 1;
  54625. /**
  54626. * Gets or sets the minimal initial rotation in radians.
  54627. */
  54628. this.minInitialRotation = 0;
  54629. /**
  54630. * Gets or sets the maximal initial rotation in radians.
  54631. */
  54632. this.maxInitialRotation = 0;
  54633. /**
  54634. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54635. */
  54636. this.minAngularSpeed = 0;
  54637. /**
  54638. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54639. */
  54640. this.maxAngularSpeed = 0;
  54641. /**
  54642. * The layer mask we are rendering the particles through.
  54643. */
  54644. this.layerMask = 0x0FFFFFFF;
  54645. /**
  54646. * This can help using your own shader to render the particle system.
  54647. * The according effect will be created
  54648. */
  54649. this.customShader = null;
  54650. /**
  54651. * By default particle system starts as soon as they are created. This prevents the
  54652. * automatic start to happen and let you decide when to start emitting particles.
  54653. */
  54654. this.preventAutoStart = false;
  54655. /**
  54656. * Callback triggered when the particle animation is ending.
  54657. */
  54658. this.onAnimationEnd = null;
  54659. /**
  54660. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54661. */
  54662. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54663. /**
  54664. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54665. * to override the particles.
  54666. */
  54667. this.forceDepthWrite = false;
  54668. /**
  54669. * You can use gravity if you want to give an orientation to your particles.
  54670. */
  54671. this.gravity = BABYLON.Vector3.Zero();
  54672. this._colorGradients = null;
  54673. this._sizeGradients = null;
  54674. this._lifeTimeGradients = null;
  54675. this._angularSpeedGradients = null;
  54676. this._velocityGradients = null;
  54677. /**
  54678. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54679. */
  54680. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54681. /**
  54682. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54683. */
  54684. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54685. /**
  54686. * Color the particle will have at the end of its lifetime
  54687. */
  54688. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54689. /**
  54690. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54691. */
  54692. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54693. /**
  54694. * 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)
  54695. */
  54696. this.spriteCellChangeSpeed = 1;
  54697. /**
  54698. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  54699. */
  54700. this.startSpriteCellID = 0;
  54701. /**
  54702. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  54703. */
  54704. this.endSpriteCellID = 0;
  54705. /**
  54706. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  54707. */
  54708. this.spriteCellWidth = 0;
  54709. /**
  54710. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  54711. */
  54712. this.spriteCellHeight = 0;
  54713. /** 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 */
  54714. this.preWarmCycles = 0;
  54715. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  54716. this.preWarmStepOffset = 1;
  54717. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  54718. this.translationPivot = new BABYLON.Vector2(0, 0);
  54719. /**
  54720. * An event triggered when the system is disposed
  54721. */
  54722. this.onDisposeObservable = new BABYLON.Observable();
  54723. /**
  54724. * Gets or sets the billboard mode to use when isBillboardBased = true.
  54725. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  54726. */
  54727. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54728. this._particles = new Array();
  54729. this._stockParticles = new Array();
  54730. this._newPartsExcess = 0;
  54731. this._vertexBuffers = {};
  54732. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54733. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54734. this._scaledDirection = BABYLON.Vector3.Zero();
  54735. this._scaledGravity = BABYLON.Vector3.Zero();
  54736. this._currentRenderId = -1;
  54737. this._useInstancing = false;
  54738. this._started = false;
  54739. this._stopped = false;
  54740. this._actualFrame = 0;
  54741. this._isBillboardBased = true;
  54742. // start of sub system methods
  54743. /**
  54744. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54745. * Its lifetime will start back at 0.
  54746. */
  54747. this.recycleParticle = function (particle) {
  54748. var lastParticle = _this._particles.pop();
  54749. if (lastParticle !== particle) {
  54750. lastParticle.copyTo(particle);
  54751. }
  54752. _this._stockParticles.push(lastParticle);
  54753. };
  54754. this._createParticle = function () {
  54755. var particle;
  54756. if (_this._stockParticles.length !== 0) {
  54757. particle = _this._stockParticles.pop();
  54758. particle.age = 0;
  54759. particle._currentColorGradient = null;
  54760. particle.cellIndex = _this.startSpriteCellID;
  54761. }
  54762. else {
  54763. particle = new BABYLON.Particle(_this);
  54764. }
  54765. return particle;
  54766. };
  54767. this._emitFromParticle = function (particle) {
  54768. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54769. return;
  54770. }
  54771. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54772. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54773. subSystem._rootParticleSystem = _this;
  54774. _this.activeSubSystems.push(subSystem);
  54775. subSystem.start();
  54776. };
  54777. this.id = name;
  54778. this.name = name;
  54779. this._capacity = capacity;
  54780. this._epsilon = epsilon;
  54781. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54782. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54783. this._customEffect = customEffect;
  54784. scene.particleSystems.push(this);
  54785. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  54786. this._createIndexBuffer();
  54787. this._createVertexBuffers();
  54788. // Default emitter type
  54789. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54790. this.updateFunction = function (particles) {
  54791. var _loop_1 = function () {
  54792. particle = particles[index];
  54793. particle.age += _this._scaledUpdateSpeed;
  54794. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  54795. _this._emitFromParticle(particle);
  54796. _this.recycleParticle(particle);
  54797. index--;
  54798. return "continue";
  54799. }
  54800. else {
  54801. var ratio = particle.age / particle.lifeTime;
  54802. // Color
  54803. if (_this._colorGradients && _this._colorGradients.length > 0) {
  54804. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  54805. if (currentGradient !== particle._currentColorGradient) {
  54806. particle._currentColor1.copyFrom(particle._currentColor2);
  54807. nextGradient.getColorToRef(particle._currentColor2);
  54808. particle._currentColorGradient = currentGradient;
  54809. }
  54810. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  54811. });
  54812. }
  54813. else {
  54814. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54815. particle.color.addInPlace(_this._scaledColorStep);
  54816. if (particle.color.a < 0) {
  54817. particle.color.a = 0;
  54818. }
  54819. }
  54820. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  54821. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  54822. if (currentGradient !== particle._currentAngularSpeedGradient) {
  54823. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  54824. particle._currentAngularSpeed2 = nextGradient.getFactor();
  54825. particle._currentAngularSpeedGradient = currentGradient;
  54826. }
  54827. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  54828. });
  54829. }
  54830. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54831. var directionScale_1 = _this._scaledUpdateSpeed;
  54832. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  54833. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  54834. if (currentGradient !== particle._currentVelocityGradient) {
  54835. particle._currentVelocity1 = particle._currentVelocity2;
  54836. particle._currentVelocity2 = nextGradient.getFactor();
  54837. particle._currentVelocityGradient = currentGradient;
  54838. }
  54839. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  54840. });
  54841. }
  54842. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  54843. particle.position.addInPlace(_this._scaledDirection);
  54844. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54845. particle.direction.addInPlace(_this._scaledGravity);
  54846. // Size
  54847. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  54848. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  54849. if (currentGradient !== particle._currentSizeGradient) {
  54850. particle._currentSize1 = particle._currentSize2;
  54851. particle._currentSize2 = nextGradient.getFactor();
  54852. particle._currentSizeGradient = currentGradient;
  54853. }
  54854. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  54855. });
  54856. }
  54857. if (_this._isAnimationSheetEnabled) {
  54858. particle.updateCellIndex();
  54859. }
  54860. }
  54861. };
  54862. var particle;
  54863. for (var index = 0; index < particles.length; index++) {
  54864. _loop_1();
  54865. }
  54866. };
  54867. }
  54868. /**
  54869. * Gets the current list of color gradients.
  54870. * You must use addColorGradient and removeColorGradient to udpate this list
  54871. * @returns the list of color gradients
  54872. */
  54873. ParticleSystem.prototype.getColorGradients = function () {
  54874. return this._colorGradients;
  54875. };
  54876. /**
  54877. * Gets the current list of size gradients.
  54878. * You must use addSizeGradient and removeSizeGradient to udpate this list
  54879. * @returns the list of size gradients
  54880. */
  54881. ParticleSystem.prototype.getSizeGradients = function () {
  54882. return this._sizeGradients;
  54883. };
  54884. /**
  54885. * Gets the current list of life time gradients.
  54886. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  54887. * @returns the list of life time gradients
  54888. */
  54889. ParticleSystem.prototype.getLifeTimeGradients = function () {
  54890. return this._lifeTimeGradients;
  54891. };
  54892. /**
  54893. * Gets the current list of angular speed gradients.
  54894. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  54895. * @returns the list of angular speed gradients
  54896. */
  54897. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  54898. return this._angularSpeedGradients;
  54899. };
  54900. /**
  54901. * Gets the current list of velocity gradients.
  54902. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  54903. * @returns the list of velocity gradients
  54904. */
  54905. ParticleSystem.prototype.getVelocityGradients = function () {
  54906. return this._velocityGradients;
  54907. };
  54908. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54909. /**
  54910. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54911. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54912. */
  54913. get: function () {
  54914. if (this.particleEmitterType.direction1) {
  54915. return this.particleEmitterType.direction1;
  54916. }
  54917. return BABYLON.Vector3.Zero();
  54918. },
  54919. set: function (value) {
  54920. if (this.particleEmitterType.direction1) {
  54921. this.particleEmitterType.direction1 = value;
  54922. }
  54923. },
  54924. enumerable: true,
  54925. configurable: true
  54926. });
  54927. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54928. /**
  54929. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54930. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54931. */
  54932. get: function () {
  54933. if (this.particleEmitterType.direction2) {
  54934. return this.particleEmitterType.direction2;
  54935. }
  54936. return BABYLON.Vector3.Zero();
  54937. },
  54938. set: function (value) {
  54939. if (this.particleEmitterType.direction2) {
  54940. this.particleEmitterType.direction2 = value;
  54941. }
  54942. },
  54943. enumerable: true,
  54944. configurable: true
  54945. });
  54946. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54947. /**
  54948. * 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.
  54949. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54950. */
  54951. get: function () {
  54952. if (this.particleEmitterType.minEmitBox) {
  54953. return this.particleEmitterType.minEmitBox;
  54954. }
  54955. return BABYLON.Vector3.Zero();
  54956. },
  54957. set: function (value) {
  54958. if (this.particleEmitterType.minEmitBox) {
  54959. this.particleEmitterType.minEmitBox = value;
  54960. }
  54961. },
  54962. enumerable: true,
  54963. configurable: true
  54964. });
  54965. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54966. /**
  54967. * 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.
  54968. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54969. */
  54970. get: function () {
  54971. if (this.particleEmitterType.maxEmitBox) {
  54972. return this.particleEmitterType.maxEmitBox;
  54973. }
  54974. return BABYLON.Vector3.Zero();
  54975. },
  54976. set: function (value) {
  54977. if (this.particleEmitterType.maxEmitBox) {
  54978. this.particleEmitterType.maxEmitBox = value;
  54979. }
  54980. },
  54981. enumerable: true,
  54982. configurable: true
  54983. });
  54984. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54985. /**
  54986. * Sets a callback that will be triggered when the system is disposed
  54987. */
  54988. set: function (callback) {
  54989. if (this._onDisposeObserver) {
  54990. this.onDisposeObservable.remove(this._onDisposeObserver);
  54991. }
  54992. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54993. },
  54994. enumerable: true,
  54995. configurable: true
  54996. });
  54997. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54998. /**
  54999. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55000. */
  55001. get: function () {
  55002. return this._isAnimationSheetEnabled;
  55003. },
  55004. enumerable: true,
  55005. configurable: true
  55006. });
  55007. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55008. /**
  55009. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55010. */
  55011. get: function () {
  55012. return this._isBillboardBased;
  55013. },
  55014. set: function (value) {
  55015. if (this._isBillboardBased === value) {
  55016. return;
  55017. }
  55018. this._isBillboardBased = value;
  55019. this._resetEffect();
  55020. },
  55021. enumerable: true,
  55022. configurable: true
  55023. });
  55024. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55025. //end of Sub-emitter
  55026. /**
  55027. * Gets the current list of active particles
  55028. */
  55029. get: function () {
  55030. return this._particles;
  55031. },
  55032. enumerable: true,
  55033. configurable: true
  55034. });
  55035. /**
  55036. * Returns the string "ParticleSystem"
  55037. * @returns a string containing the class name
  55038. */
  55039. ParticleSystem.prototype.getClassName = function () {
  55040. return "ParticleSystem";
  55041. };
  55042. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55043. var newGradient = new BABYLON.FactorGradient();
  55044. newGradient.gradient = gradient;
  55045. newGradient.factor1 = factor;
  55046. newGradient.factor2 = factor2;
  55047. factorGradients.push(newGradient);
  55048. factorGradients.sort(function (a, b) {
  55049. if (a.gradient < b.gradient) {
  55050. return -1;
  55051. }
  55052. else if (a.gradient > b.gradient) {
  55053. return 1;
  55054. }
  55055. return 0;
  55056. });
  55057. };
  55058. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55059. if (!factorGradients) {
  55060. return;
  55061. }
  55062. var index = 0;
  55063. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55064. var factorGradient = factorGradients_1[_i];
  55065. if (factorGradient.gradient === gradient) {
  55066. factorGradients.splice(index, 1);
  55067. break;
  55068. }
  55069. index++;
  55070. }
  55071. };
  55072. /**
  55073. * Adds a new life time gradient
  55074. * @param gradient defines the gradient to use (between 0 and 1)
  55075. * @param factor defines the life time factor to affect to the specified gradient
  55076. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55077. * @returns the current particle system
  55078. */
  55079. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55080. if (!this._lifeTimeGradients) {
  55081. this._lifeTimeGradients = [];
  55082. }
  55083. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55084. return this;
  55085. };
  55086. /**
  55087. * Remove a specific life time gradient
  55088. * @param gradient defines the gradient to remove
  55089. * @returns the current particle system
  55090. */
  55091. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55092. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55093. return this;
  55094. };
  55095. /**
  55096. * Adds a new size gradient
  55097. * @param gradient defines the gradient to use (between 0 and 1)
  55098. * @param factor defines the size factor to affect to the specified gradient
  55099. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55100. * @returns the current particle system
  55101. */
  55102. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55103. if (!this._sizeGradients) {
  55104. this._sizeGradients = [];
  55105. }
  55106. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55107. return this;
  55108. };
  55109. /**
  55110. * Remove a specific size gradient
  55111. * @param gradient defines the gradient to remove
  55112. * @returns the current particle system
  55113. */
  55114. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55115. this._removeFactorGradient(this._sizeGradients, gradient);
  55116. return this;
  55117. };
  55118. /**
  55119. * Adds a new angular speed gradient
  55120. * @param gradient defines the gradient to use (between 0 and 1)
  55121. * @param factor defines the size factor to affect to the specified gradient
  55122. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55123. * @returns the current particle system
  55124. */
  55125. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55126. if (!this._angularSpeedGradients) {
  55127. this._angularSpeedGradients = [];
  55128. }
  55129. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55130. return this;
  55131. };
  55132. /**
  55133. * Remove a specific angular speed gradient
  55134. * @param gradient defines the gradient to remove
  55135. * @returns the current particle system
  55136. */
  55137. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55138. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55139. return this;
  55140. };
  55141. /**
  55142. * Adds a new velocity gradient
  55143. * @param gradient defines the gradient to use (between 0 and 1)
  55144. * @param factor defines the size factor to affect to the specified gradient
  55145. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55146. * @returns the current particle system
  55147. */
  55148. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55149. if (!this._velocityGradients) {
  55150. this._velocityGradients = [];
  55151. }
  55152. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55153. return this;
  55154. };
  55155. /**
  55156. * Remove a specific velocity gradient
  55157. * @param gradient defines the gradient to remove
  55158. * @returns the current particle system
  55159. */
  55160. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55161. this._removeFactorGradient(this._velocityGradients, gradient);
  55162. return this;
  55163. };
  55164. /**
  55165. * Adds a new color gradient
  55166. * @param gradient defines the gradient to use (between 0 and 1)
  55167. * @param color defines the color to affect to the specified gradient
  55168. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55169. */
  55170. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55171. if (!this._colorGradients) {
  55172. this._colorGradients = [];
  55173. }
  55174. var colorGradient = new BABYLON.ColorGradient();
  55175. colorGradient.gradient = gradient;
  55176. colorGradient.color1 = color;
  55177. colorGradient.color2 = color2;
  55178. this._colorGradients.push(colorGradient);
  55179. this._colorGradients.sort(function (a, b) {
  55180. if (a.gradient < b.gradient) {
  55181. return -1;
  55182. }
  55183. else if (a.gradient > b.gradient) {
  55184. return 1;
  55185. }
  55186. return 0;
  55187. });
  55188. return this;
  55189. };
  55190. /**
  55191. * Remove a specific color gradient
  55192. * @param gradient defines the gradient to remove
  55193. */
  55194. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55195. if (!this._colorGradients) {
  55196. return this;
  55197. }
  55198. var index = 0;
  55199. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55200. var colorGradient = _a[_i];
  55201. if (colorGradient.gradient === gradient) {
  55202. this._colorGradients.splice(index, 1);
  55203. break;
  55204. }
  55205. index++;
  55206. }
  55207. return this;
  55208. };
  55209. ParticleSystem.prototype._resetEffect = function () {
  55210. if (this._vertexBuffer) {
  55211. this._vertexBuffer.dispose();
  55212. this._vertexBuffer = null;
  55213. }
  55214. if (this._spriteBuffer) {
  55215. this._spriteBuffer.dispose();
  55216. this._spriteBuffer = null;
  55217. }
  55218. this._createVertexBuffers();
  55219. };
  55220. ParticleSystem.prototype._createVertexBuffers = function () {
  55221. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55222. if (this._isAnimationSheetEnabled) {
  55223. this._vertexBufferSize += 1;
  55224. }
  55225. if (!this._isBillboardBased) {
  55226. this._vertexBufferSize += 3;
  55227. }
  55228. var engine = this._scene.getEngine();
  55229. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55230. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55231. var dataOffset = 0;
  55232. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55233. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55234. dataOffset += 3;
  55235. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55236. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55237. dataOffset += 4;
  55238. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55239. this._vertexBuffers["angle"] = options;
  55240. dataOffset += 1;
  55241. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55242. this._vertexBuffers["size"] = size;
  55243. dataOffset += 2;
  55244. if (this._isAnimationSheetEnabled) {
  55245. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55246. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55247. dataOffset += 1;
  55248. }
  55249. if (!this._isBillboardBased) {
  55250. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55251. this._vertexBuffers["direction"] = directionBuffer;
  55252. dataOffset += 3;
  55253. }
  55254. var offsets;
  55255. if (this._useInstancing) {
  55256. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55257. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55258. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55259. }
  55260. else {
  55261. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55262. dataOffset += 2;
  55263. }
  55264. this._vertexBuffers["offset"] = offsets;
  55265. };
  55266. ParticleSystem.prototype._createIndexBuffer = function () {
  55267. if (this._useInstancing) {
  55268. return;
  55269. }
  55270. var indices = [];
  55271. var index = 0;
  55272. for (var count = 0; count < this._capacity; count++) {
  55273. indices.push(index);
  55274. indices.push(index + 1);
  55275. indices.push(index + 2);
  55276. indices.push(index);
  55277. indices.push(index + 2);
  55278. indices.push(index + 3);
  55279. index += 4;
  55280. }
  55281. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55282. };
  55283. /**
  55284. * Gets the maximum number of particles active at the same time.
  55285. * @returns The max number of active particles.
  55286. */
  55287. ParticleSystem.prototype.getCapacity = function () {
  55288. return this._capacity;
  55289. };
  55290. /**
  55291. * Gets Wether there are still active particles in the system.
  55292. * @returns True if it is alive, otherwise false.
  55293. */
  55294. ParticleSystem.prototype.isAlive = function () {
  55295. return this._alive;
  55296. };
  55297. /**
  55298. * Gets Wether the system has been started.
  55299. * @returns True if it has been started, otherwise false.
  55300. */
  55301. ParticleSystem.prototype.isStarted = function () {
  55302. return this._started;
  55303. };
  55304. /**
  55305. * Starts the particle system and begins to emit.
  55306. */
  55307. ParticleSystem.prototype.start = function () {
  55308. this._started = true;
  55309. this._stopped = false;
  55310. this._actualFrame = 0;
  55311. if (this.subEmitters && this.subEmitters.length != 0) {
  55312. this.activeSubSystems = new Array();
  55313. }
  55314. if (this.preWarmCycles) {
  55315. for (var index = 0; index < this.preWarmCycles; index++) {
  55316. this.animate(true);
  55317. }
  55318. }
  55319. };
  55320. /**
  55321. * Stops the particle system.
  55322. * @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.
  55323. */
  55324. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55325. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55326. this._stopped = true;
  55327. if (stopSubEmitters) {
  55328. this._stopSubEmitters();
  55329. }
  55330. };
  55331. // animation sheet
  55332. /**
  55333. * Remove all active particles
  55334. */
  55335. ParticleSystem.prototype.reset = function () {
  55336. this._stockParticles = [];
  55337. this._particles = [];
  55338. };
  55339. /**
  55340. * @hidden (for internal use only)
  55341. */
  55342. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55343. var offset = index * this._vertexBufferSize;
  55344. this._vertexData[offset++] = particle.position.x;
  55345. this._vertexData[offset++] = particle.position.y;
  55346. this._vertexData[offset++] = particle.position.z;
  55347. this._vertexData[offset++] = particle.color.r;
  55348. this._vertexData[offset++] = particle.color.g;
  55349. this._vertexData[offset++] = particle.color.b;
  55350. this._vertexData[offset++] = particle.color.a;
  55351. this._vertexData[offset++] = particle.angle;
  55352. this._vertexData[offset++] = particle.scale.x * particle.size;
  55353. this._vertexData[offset++] = particle.scale.y * particle.size;
  55354. if (this._isAnimationSheetEnabled) {
  55355. this._vertexData[offset++] = particle.cellIndex;
  55356. }
  55357. if (!this._isBillboardBased) {
  55358. if (particle._initialDirection) {
  55359. this._vertexData[offset++] = particle._initialDirection.x;
  55360. this._vertexData[offset++] = particle._initialDirection.y;
  55361. this._vertexData[offset++] = particle._initialDirection.z;
  55362. }
  55363. else {
  55364. this._vertexData[offset++] = particle.direction.x;
  55365. this._vertexData[offset++] = particle.direction.y;
  55366. this._vertexData[offset++] = particle.direction.z;
  55367. }
  55368. }
  55369. if (!this._useInstancing) {
  55370. if (this._isAnimationSheetEnabled) {
  55371. if (offsetX === 0)
  55372. offsetX = this._epsilon;
  55373. else if (offsetX === 1)
  55374. offsetX = 1 - this._epsilon;
  55375. if (offsetY === 0)
  55376. offsetY = this._epsilon;
  55377. else if (offsetY === 1)
  55378. offsetY = 1 - this._epsilon;
  55379. }
  55380. this._vertexData[offset++] = offsetX;
  55381. this._vertexData[offset++] = offsetY;
  55382. }
  55383. };
  55384. ParticleSystem.prototype._stopSubEmitters = function () {
  55385. if (!this.activeSubSystems) {
  55386. return;
  55387. }
  55388. this.activeSubSystems.forEach(function (subSystem) {
  55389. subSystem.stop(true);
  55390. });
  55391. this.activeSubSystems = new Array();
  55392. };
  55393. ParticleSystem.prototype._removeFromRoot = function () {
  55394. if (!this._rootParticleSystem) {
  55395. return;
  55396. }
  55397. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55398. if (index !== -1) {
  55399. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55400. }
  55401. };
  55402. // End of sub system methods
  55403. ParticleSystem.prototype._update = function (newParticles) {
  55404. // Update current
  55405. this._alive = this._particles.length > 0;
  55406. this.updateFunction(this._particles);
  55407. // Add new ones
  55408. var worldMatrix;
  55409. if (this.emitter.position) {
  55410. var emitterMesh = this.emitter;
  55411. worldMatrix = emitterMesh.getWorldMatrix();
  55412. }
  55413. else {
  55414. var emitterPosition = this.emitter;
  55415. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55416. }
  55417. var particle;
  55418. var _loop_2 = function () {
  55419. if (this_1._particles.length === this_1._capacity) {
  55420. return "break";
  55421. }
  55422. particle = this_1._createParticle();
  55423. this_1._particles.push(particle);
  55424. // Emitter
  55425. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55426. if (this_1.startPositionFunction) {
  55427. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55428. }
  55429. else {
  55430. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55431. }
  55432. if (this_1.startDirectionFunction) {
  55433. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55434. }
  55435. else {
  55436. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55437. }
  55438. if (emitPower === 0) {
  55439. if (!particle._initialDirection) {
  55440. particle._initialDirection = particle.direction.clone();
  55441. }
  55442. else {
  55443. particle._initialDirection.copyFrom(particle.direction);
  55444. }
  55445. }
  55446. else {
  55447. particle._initialDirection = null;
  55448. }
  55449. particle.direction.scaleInPlace(emitPower);
  55450. // Life time
  55451. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55452. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55453. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55454. var factorGradient1 = currentGradient;
  55455. var factorGradient2 = nextGradient;
  55456. var lifeTime1 = factorGradient1.getFactor();
  55457. var lifeTime2 = factorGradient2.getFactor();
  55458. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55459. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55460. });
  55461. }
  55462. else {
  55463. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55464. }
  55465. // Size
  55466. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55467. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55468. }
  55469. else {
  55470. particle._currentSizeGradient = this_1._sizeGradients[0];
  55471. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55472. particle.size = particle._currentSize1;
  55473. if (this_1._sizeGradients.length > 1) {
  55474. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55475. }
  55476. else {
  55477. particle._currentSize2 = particle._currentSize1;
  55478. }
  55479. }
  55480. // Size and scale
  55481. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55482. // Angle
  55483. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55484. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55485. }
  55486. else {
  55487. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55488. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55489. particle._currentAngularSpeed1 = particle.angularSpeed;
  55490. if (this_1._angularSpeedGradients.length > 1) {
  55491. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55492. }
  55493. else {
  55494. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55495. }
  55496. }
  55497. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55498. // Velocity
  55499. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55500. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55501. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55502. if (this_1._velocityGradients.length > 1) {
  55503. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55504. }
  55505. else {
  55506. particle._currentVelocity2 = particle._currentVelocity1;
  55507. }
  55508. }
  55509. // Color
  55510. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55511. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55512. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55513. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55514. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55515. }
  55516. else {
  55517. particle._currentColorGradient = this_1._colorGradients[0];
  55518. particle._currentColorGradient.getColorToRef(particle.color);
  55519. particle._currentColor1.copyFrom(particle.color);
  55520. if (this_1._colorGradients.length > 1) {
  55521. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55522. }
  55523. else {
  55524. particle._currentColor2.copyFrom(particle.color);
  55525. }
  55526. }
  55527. // Sheet
  55528. if (this_1._isAnimationSheetEnabled) {
  55529. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55530. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55531. }
  55532. };
  55533. var this_1 = this, step;
  55534. for (var index = 0; index < newParticles; index++) {
  55535. var state_1 = _loop_2();
  55536. if (state_1 === "break")
  55537. break;
  55538. }
  55539. };
  55540. /** @hidden */
  55541. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55542. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55543. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55544. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55545. if (isAnimationSheetEnabled) {
  55546. attributeNamesOrOptions.push("cellIndex");
  55547. }
  55548. if (!isBillboardBased) {
  55549. attributeNamesOrOptions.push("direction");
  55550. }
  55551. return attributeNamesOrOptions;
  55552. };
  55553. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55554. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55555. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55556. if (isAnimationSheetEnabled) {
  55557. effectCreationOption.push("particlesInfos");
  55558. }
  55559. return effectCreationOption;
  55560. };
  55561. ParticleSystem.prototype._getEffect = function () {
  55562. if (this._customEffect) {
  55563. return this._customEffect;
  55564. }
  55565. ;
  55566. var defines = [];
  55567. if (this._scene.clipPlane) {
  55568. defines.push("#define CLIPPLANE");
  55569. }
  55570. if (this._isAnimationSheetEnabled) {
  55571. defines.push("#define ANIMATESHEET");
  55572. }
  55573. if (this._isBillboardBased) {
  55574. defines.push("#define BILLBOARD");
  55575. switch (this.billboardMode) {
  55576. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55577. defines.push("#define BILLBOARDY");
  55578. break;
  55579. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55580. default:
  55581. break;
  55582. }
  55583. }
  55584. // Effect
  55585. var join = defines.join("\n");
  55586. if (this._cachedDefines !== join) {
  55587. this._cachedDefines = join;
  55588. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55589. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55590. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55591. }
  55592. return this._effect;
  55593. };
  55594. /**
  55595. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55596. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55597. */
  55598. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55599. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55600. if (!this._started)
  55601. return;
  55602. if (!preWarmOnly) {
  55603. var effect = this._getEffect();
  55604. // Check
  55605. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55606. return;
  55607. if (this._currentRenderId === this._scene.getRenderId()) {
  55608. return;
  55609. }
  55610. this._currentRenderId = this._scene.getRenderId();
  55611. }
  55612. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55613. // determine the number of particles we need to create
  55614. var newParticles;
  55615. if (this.manualEmitCount > -1) {
  55616. newParticles = this.manualEmitCount;
  55617. this._newPartsExcess = 0;
  55618. this.manualEmitCount = 0;
  55619. }
  55620. else {
  55621. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55622. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55623. }
  55624. if (this._newPartsExcess > 1.0) {
  55625. newParticles += this._newPartsExcess >> 0;
  55626. this._newPartsExcess -= this._newPartsExcess >> 0;
  55627. }
  55628. this._alive = false;
  55629. if (!this._stopped) {
  55630. this._actualFrame += this._scaledUpdateSpeed;
  55631. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55632. this.stop();
  55633. }
  55634. else {
  55635. newParticles = 0;
  55636. }
  55637. this._update(newParticles);
  55638. // Stopped?
  55639. if (this._stopped) {
  55640. if (!this._alive) {
  55641. this._started = false;
  55642. if (this.onAnimationEnd) {
  55643. this.onAnimationEnd();
  55644. }
  55645. if (this.disposeOnStop) {
  55646. this._scene._toBeDisposed.push(this);
  55647. }
  55648. }
  55649. }
  55650. if (!preWarmOnly) {
  55651. // Update VBO
  55652. var offset = 0;
  55653. for (var index = 0; index < this._particles.length; index++) {
  55654. var particle = this._particles[index];
  55655. this._appendParticleVertices(offset, particle);
  55656. offset += this._useInstancing ? 1 : 4;
  55657. }
  55658. if (this._vertexBuffer) {
  55659. this._vertexBuffer.update(this._vertexData);
  55660. }
  55661. }
  55662. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55663. this.stop();
  55664. }
  55665. };
  55666. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55667. this._appendParticleVertex(offset++, particle, 0, 0);
  55668. if (!this._useInstancing) {
  55669. this._appendParticleVertex(offset++, particle, 1, 0);
  55670. this._appendParticleVertex(offset++, particle, 1, 1);
  55671. this._appendParticleVertex(offset++, particle, 0, 1);
  55672. }
  55673. };
  55674. /**
  55675. * Rebuilds the particle system.
  55676. */
  55677. ParticleSystem.prototype.rebuild = function () {
  55678. this._createIndexBuffer();
  55679. if (this._vertexBuffer) {
  55680. this._vertexBuffer._rebuild();
  55681. }
  55682. };
  55683. /**
  55684. * Is this system ready to be used/rendered
  55685. * @return true if the system is ready
  55686. */
  55687. ParticleSystem.prototype.isReady = function () {
  55688. var effect = this._getEffect();
  55689. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55690. return false;
  55691. }
  55692. return true;
  55693. };
  55694. /**
  55695. * Renders the particle system in its current state.
  55696. * @returns the current number of particles
  55697. */
  55698. ParticleSystem.prototype.render = function () {
  55699. var effect = this._getEffect();
  55700. // Check
  55701. if (!this.isReady() || !this._particles.length) {
  55702. return 0;
  55703. }
  55704. var engine = this._scene.getEngine();
  55705. // Render
  55706. engine.enableEffect(effect);
  55707. engine.setState(false);
  55708. var viewMatrix = this._scene.getViewMatrix();
  55709. effect.setTexture("diffuseSampler", this.particleTexture);
  55710. effect.setMatrix("view", viewMatrix);
  55711. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55712. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55713. var baseSize = this.particleTexture.getBaseSize();
  55714. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55715. }
  55716. effect.setVector2("translationPivot", this.translationPivot);
  55717. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55718. if (this._isBillboardBased) {
  55719. var camera = this._scene.activeCamera;
  55720. effect.setVector3("eyePosition", camera.globalPosition);
  55721. }
  55722. if (this._scene.clipPlane) {
  55723. var clipPlane = this._scene.clipPlane;
  55724. var invView = viewMatrix.clone();
  55725. invView.invert();
  55726. effect.setMatrix("invView", invView);
  55727. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55728. }
  55729. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55730. // Draw order
  55731. switch (this.blendMode) {
  55732. case ParticleSystem.BLENDMODE_ADD:
  55733. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55734. break;
  55735. case ParticleSystem.BLENDMODE_ONEONE:
  55736. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55737. break;
  55738. case ParticleSystem.BLENDMODE_STANDARD:
  55739. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55740. break;
  55741. }
  55742. if (this.forceDepthWrite) {
  55743. engine.setDepthWrite(true);
  55744. }
  55745. if (this._useInstancing) {
  55746. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55747. engine.unbindInstanceAttributes();
  55748. }
  55749. else {
  55750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55751. }
  55752. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55753. return this._particles.length;
  55754. };
  55755. /**
  55756. * Disposes the particle system and free the associated resources
  55757. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55758. */
  55759. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55760. if (disposeTexture === void 0) { disposeTexture = true; }
  55761. if (this._vertexBuffer) {
  55762. this._vertexBuffer.dispose();
  55763. this._vertexBuffer = null;
  55764. }
  55765. if (this._spriteBuffer) {
  55766. this._spriteBuffer.dispose();
  55767. this._spriteBuffer = null;
  55768. }
  55769. if (this._indexBuffer) {
  55770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55771. this._indexBuffer = null;
  55772. }
  55773. if (disposeTexture && this.particleTexture) {
  55774. this.particleTexture.dispose();
  55775. this.particleTexture = null;
  55776. }
  55777. this._removeFromRoot();
  55778. // Remove from scene
  55779. var index = this._scene.particleSystems.indexOf(this);
  55780. if (index > -1) {
  55781. this._scene.particleSystems.splice(index, 1);
  55782. }
  55783. // Callback
  55784. this.onDisposeObservable.notifyObservers(this);
  55785. this.onDisposeObservable.clear();
  55786. };
  55787. /**
  55788. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55789. * @param radius The radius of the sphere to emit from
  55790. * @returns the emitter
  55791. */
  55792. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55793. if (radius === void 0) { radius = 1; }
  55794. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55795. this.particleEmitterType = particleEmitter;
  55796. return particleEmitter;
  55797. };
  55798. /**
  55799. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55800. * @param radius The radius of the sphere to emit from
  55801. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55802. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55803. * @returns the emitter
  55804. */
  55805. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55806. if (radius === void 0) { radius = 1; }
  55807. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55808. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55809. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55810. this.particleEmitterType = particleEmitter;
  55811. return particleEmitter;
  55812. };
  55813. /**
  55814. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55815. * @param radius The radius of the cone to emit from
  55816. * @param angle The base angle of the cone
  55817. * @returns the emitter
  55818. */
  55819. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55820. if (radius === void 0) { radius = 1; }
  55821. if (angle === void 0) { angle = Math.PI / 4; }
  55822. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55823. this.particleEmitterType = particleEmitter;
  55824. return particleEmitter;
  55825. };
  55826. // 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.
  55827. /**
  55828. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55829. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55830. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55831. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55832. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55833. * @returns the emitter
  55834. */
  55835. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55836. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55837. this.particleEmitterType = particleEmitter;
  55838. this.direction1 = direction1;
  55839. this.direction2 = direction2;
  55840. this.minEmitBox = minEmitBox;
  55841. this.maxEmitBox = maxEmitBox;
  55842. return particleEmitter;
  55843. };
  55844. // Clone
  55845. /**
  55846. * Clones the particle system.
  55847. * @param name The name of the cloned object
  55848. * @param newEmitter The new emitter to use
  55849. * @returns the cloned particle system
  55850. */
  55851. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55852. var custom = null;
  55853. var program = null;
  55854. if (this.customShader != null) {
  55855. program = this.customShader;
  55856. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55857. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55858. }
  55859. else if (this._customEffect) {
  55860. custom = this._customEffect;
  55861. }
  55862. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55863. result.customShader = program;
  55864. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55865. if (newEmitter === undefined) {
  55866. newEmitter = this.emitter;
  55867. }
  55868. result.emitter = newEmitter;
  55869. if (this.particleTexture) {
  55870. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55871. }
  55872. if (!this.preventAutoStart) {
  55873. result.start();
  55874. }
  55875. return result;
  55876. };
  55877. /**
  55878. * Serializes the particle system to a JSON object.
  55879. * @returns the JSON object
  55880. */
  55881. ParticleSystem.prototype.serialize = function () {
  55882. var serializationObject = {};
  55883. ParticleSystem._Serialize(serializationObject, this);
  55884. serializationObject.textureMask = this.textureMask.asArray();
  55885. serializationObject.customShader = this.customShader;
  55886. serializationObject.preventAutoStart = this.preventAutoStart;
  55887. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55888. return serializationObject;
  55889. };
  55890. /** @hidden */
  55891. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55892. serializationObject.name = particleSystem.name;
  55893. serializationObject.id = particleSystem.id;
  55894. serializationObject.capacity = particleSystem.getCapacity();
  55895. // Emitter
  55896. if (particleSystem.emitter.position) {
  55897. var emitterMesh = particleSystem.emitter;
  55898. serializationObject.emitterId = emitterMesh.id;
  55899. }
  55900. else {
  55901. var emitterPosition = particleSystem.emitter;
  55902. serializationObject.emitter = emitterPosition.asArray();
  55903. }
  55904. // Emitter
  55905. if (particleSystem.particleEmitterType) {
  55906. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  55907. }
  55908. if (particleSystem.particleTexture) {
  55909. serializationObject.textureName = particleSystem.particleTexture.name;
  55910. }
  55911. // Animations
  55912. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  55913. // Particle system
  55914. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  55915. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  55916. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  55917. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  55918. serializationObject.minSize = particleSystem.minSize;
  55919. serializationObject.maxSize = particleSystem.maxSize;
  55920. serializationObject.minScaleX = particleSystem.minScaleX;
  55921. serializationObject.maxScaleX = particleSystem.maxScaleX;
  55922. serializationObject.minScaleY = particleSystem.minScaleY;
  55923. serializationObject.maxScaleY = particleSystem.maxScaleY;
  55924. serializationObject.minEmitPower = particleSystem.minEmitPower;
  55925. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  55926. serializationObject.minLifeTime = particleSystem.minLifeTime;
  55927. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  55928. serializationObject.emitRate = particleSystem.emitRate;
  55929. serializationObject.gravity = particleSystem.gravity.asArray();
  55930. serializationObject.color1 = particleSystem.color1.asArray();
  55931. serializationObject.color2 = particleSystem.color2.asArray();
  55932. serializationObject.colorDead = particleSystem.colorDead.asArray();
  55933. serializationObject.updateSpeed = particleSystem.updateSpeed;
  55934. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  55935. serializationObject.blendMode = particleSystem.blendMode;
  55936. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  55937. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  55938. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  55939. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  55940. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  55941. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  55942. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  55943. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  55944. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  55945. var colorGradients = particleSystem.getColorGradients();
  55946. if (colorGradients) {
  55947. serializationObject.colorGradients = [];
  55948. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  55949. var colorGradient = colorGradients_1[_i];
  55950. var serializedGradient = {
  55951. gradient: colorGradient.gradient,
  55952. color1: colorGradient.color1.asArray()
  55953. };
  55954. if (colorGradient.color2) {
  55955. serializedGradient.color2 = colorGradient.color2.asArray();
  55956. }
  55957. serializationObject.colorGradients.push(serializedGradient);
  55958. }
  55959. }
  55960. var sizeGradients = particleSystem.getSizeGradients();
  55961. if (sizeGradients) {
  55962. serializationObject.sizeGradients = [];
  55963. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  55964. var sizeGradient = sizeGradients_1[_a];
  55965. var serializedGradient = {
  55966. gradient: sizeGradient.gradient,
  55967. factor1: sizeGradient.factor1
  55968. };
  55969. if (sizeGradient.factor2 !== undefined) {
  55970. serializedGradient.factor2 = sizeGradient.factor2;
  55971. }
  55972. serializationObject.sizeGradients.push(serializedGradient);
  55973. }
  55974. }
  55975. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  55976. if (angularSpeedGradients) {
  55977. serializationObject.angularSpeedGradients = [];
  55978. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  55979. var angularSpeedGradient = angularSpeedGradients_1[_b];
  55980. var serializedGradient = {
  55981. gradient: angularSpeedGradient.gradient,
  55982. factor1: angularSpeedGradient.factor1
  55983. };
  55984. if (angularSpeedGradient.factor2 !== undefined) {
  55985. serializedGradient.factor2 = angularSpeedGradient.factor2;
  55986. }
  55987. serializationObject.angularSpeedGradients.push(serializedGradient);
  55988. }
  55989. }
  55990. var velocityGradients = particleSystem.getVelocityGradients();
  55991. if (velocityGradients) {
  55992. serializationObject.velocityGradients = [];
  55993. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  55994. var velocityGradient = velocityGradients_1[_c];
  55995. var serializedGradient = {
  55996. gradient: velocityGradient.gradient,
  55997. factor1: velocityGradient.factor1
  55998. };
  55999. if (velocityGradient.factor2 !== undefined) {
  56000. serializedGradient.factor2 = velocityGradient.factor2;
  56001. }
  56002. serializationObject.velocityGradients.push(serializedGradient);
  56003. }
  56004. }
  56005. };
  56006. /** @hidden */
  56007. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56008. // Texture
  56009. if (parsedParticleSystem.textureName) {
  56010. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56011. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56012. }
  56013. // Emitter
  56014. if (parsedParticleSystem.emitterId === undefined) {
  56015. particleSystem.emitter = BABYLON.Vector3.Zero();
  56016. }
  56017. else if (parsedParticleSystem.emitterId) {
  56018. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56019. }
  56020. else {
  56021. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56022. }
  56023. // Misc.
  56024. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56025. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56026. }
  56027. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56028. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56029. }
  56030. // Animations
  56031. if (parsedParticleSystem.animations) {
  56032. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56033. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56034. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56035. }
  56036. }
  56037. if (parsedParticleSystem.autoAnimate) {
  56038. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56039. }
  56040. // Particle system
  56041. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56042. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56043. particleSystem.minSize = parsedParticleSystem.minSize;
  56044. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56045. if (parsedParticleSystem.minScaleX) {
  56046. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56047. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56048. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56049. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56050. }
  56051. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56052. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56053. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56054. }
  56055. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56056. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56057. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56058. }
  56059. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56060. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56061. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56062. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56063. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56064. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56065. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56066. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56067. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56068. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56069. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56070. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56071. if (parsedParticleSystem.colorGradients) {
  56072. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56073. var colorGradient = _a[_i];
  56074. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56075. }
  56076. }
  56077. if (parsedParticleSystem.sizeGradients) {
  56078. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56079. var sizeGradient = _c[_b];
  56080. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56081. }
  56082. }
  56083. if (parsedParticleSystem.angularSpeedGradients) {
  56084. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56085. var angularSpeedGradient = _e[_d];
  56086. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56087. }
  56088. }
  56089. if (parsedParticleSystem.velocityGradients) {
  56090. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56091. var velocityGradient = _g[_f];
  56092. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56093. }
  56094. }
  56095. // Emitter
  56096. var emitterType;
  56097. if (parsedParticleSystem.particleEmitterType) {
  56098. switch (parsedParticleSystem.particleEmitterType.type) {
  56099. case "SphereParticleEmitter":
  56100. emitterType = new BABYLON.SphereParticleEmitter();
  56101. break;
  56102. case "SphereDirectedParticleEmitter":
  56103. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56104. break;
  56105. case "ConeEmitter":
  56106. case "ConeParticleEmitter":
  56107. emitterType = new BABYLON.ConeParticleEmitter();
  56108. break;
  56109. case "BoxEmitter":
  56110. case "BoxParticleEmitter":
  56111. default:
  56112. emitterType = new BABYLON.BoxParticleEmitter();
  56113. break;
  56114. }
  56115. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56116. }
  56117. else {
  56118. emitterType = new BABYLON.BoxParticleEmitter();
  56119. emitterType.parse(parsedParticleSystem);
  56120. }
  56121. particleSystem.particleEmitterType = emitterType;
  56122. // Animation sheet
  56123. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56124. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56125. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56126. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56127. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56128. };
  56129. /**
  56130. * Parses a JSON object to create a particle system.
  56131. * @param parsedParticleSystem The JSON object to parse
  56132. * @param scene The scene to create the particle system in
  56133. * @param rootUrl The root url to use to load external dependencies like texture
  56134. * @returns the Parsed particle system
  56135. */
  56136. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56137. var name = parsedParticleSystem.name;
  56138. var custom = null;
  56139. var program = null;
  56140. if (parsedParticleSystem.customShader) {
  56141. program = parsedParticleSystem.customShader;
  56142. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56143. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56144. }
  56145. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56146. particleSystem.customShader = program;
  56147. if (parsedParticleSystem.id) {
  56148. particleSystem.id = parsedParticleSystem.id;
  56149. }
  56150. // Auto start
  56151. if (parsedParticleSystem.preventAutoStart) {
  56152. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56153. }
  56154. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56155. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56156. if (!particleSystem.preventAutoStart) {
  56157. particleSystem.start();
  56158. }
  56159. return particleSystem;
  56160. };
  56161. /**
  56162. * Source color is added to the destination color without alpha affecting the result.
  56163. */
  56164. ParticleSystem.BLENDMODE_ONEONE = 0;
  56165. /**
  56166. * Blend current color and particle color using particle’s alpha.
  56167. */
  56168. ParticleSystem.BLENDMODE_STANDARD = 1;
  56169. /**
  56170. * Add current color and particle color multiplied by particle’s alpha.
  56171. */
  56172. ParticleSystem.BLENDMODE_ADD = 2;
  56173. return ParticleSystem;
  56174. }());
  56175. BABYLON.ParticleSystem = ParticleSystem;
  56176. })(BABYLON || (BABYLON = {}));
  56177. //# sourceMappingURL=babylon.particleSystem.js.map
  56178. var BABYLON;
  56179. (function (BABYLON) {
  56180. /**
  56181. * Particle emitter emitting particles from the inside of a box.
  56182. * It emits the particles randomly between 2 given directions.
  56183. */
  56184. var BoxParticleEmitter = /** @class */ (function () {
  56185. /**
  56186. * Creates a new instance BoxParticleEmitter
  56187. */
  56188. function BoxParticleEmitter() {
  56189. /**
  56190. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56191. */
  56192. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56193. /**
  56194. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56195. */
  56196. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56197. /**
  56198. * 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.
  56199. */
  56200. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56201. /**
  56202. * 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.
  56203. */
  56204. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56205. }
  56206. /**
  56207. * Called by the particle System when the direction is computed for the created particle.
  56208. * @param worldMatrix is the world matrix of the particle system
  56209. * @param directionToUpdate is the direction vector to update with the result
  56210. * @param particle is the particle we are computed the direction for
  56211. */
  56212. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56213. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56214. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56215. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56216. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56217. };
  56218. /**
  56219. * Called by the particle System when the position is computed for the created particle.
  56220. * @param worldMatrix is the world matrix of the particle system
  56221. * @param positionToUpdate is the position vector to update with the result
  56222. * @param particle is the particle we are computed the position for
  56223. */
  56224. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56225. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56226. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56227. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56229. };
  56230. /**
  56231. * Clones the current emitter and returns a copy of it
  56232. * @returns the new emitter
  56233. */
  56234. BoxParticleEmitter.prototype.clone = function () {
  56235. var newOne = new BoxParticleEmitter();
  56236. BABYLON.Tools.DeepCopy(this, newOne);
  56237. return newOne;
  56238. };
  56239. /**
  56240. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56241. * @param effect defines the update shader
  56242. */
  56243. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56244. effect.setVector3("direction1", this.direction1);
  56245. effect.setVector3("direction2", this.direction2);
  56246. effect.setVector3("minEmitBox", this.minEmitBox);
  56247. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56248. };
  56249. /**
  56250. * Returns a string to use to update the GPU particles update shader
  56251. * @returns a string containng the defines string
  56252. */
  56253. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56254. return "#define BOXEMITTER";
  56255. };
  56256. /**
  56257. * Returns the string "BoxParticleEmitter"
  56258. * @returns a string containing the class name
  56259. */
  56260. BoxParticleEmitter.prototype.getClassName = function () {
  56261. return "BoxParticleEmitter";
  56262. };
  56263. /**
  56264. * Serializes the particle system to a JSON object.
  56265. * @returns the JSON object
  56266. */
  56267. BoxParticleEmitter.prototype.serialize = function () {
  56268. var serializationObject = {};
  56269. serializationObject.type = this.getClassName();
  56270. serializationObject.direction1 = this.direction1.asArray();
  56271. serializationObject.direction2 = this.direction2.asArray();
  56272. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56273. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56274. return serializationObject;
  56275. };
  56276. /**
  56277. * Parse properties from a JSON object
  56278. * @param serializationObject defines the JSON object
  56279. */
  56280. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56281. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56282. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56283. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56284. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56285. };
  56286. return BoxParticleEmitter;
  56287. }());
  56288. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56289. })(BABYLON || (BABYLON = {}));
  56290. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56291. var BABYLON;
  56292. (function (BABYLON) {
  56293. /**
  56294. * Particle emitter emitting particles from the inside of a cone.
  56295. * It emits the particles alongside the cone volume from the base to the particle.
  56296. * The emission direction might be randomized.
  56297. */
  56298. var ConeParticleEmitter = /** @class */ (function () {
  56299. /**
  56300. * Creates a new instance ConeParticleEmitter
  56301. * @param radius the radius of the emission cone (1 by default)
  56302. * @param angles the cone base angle (PI by default)
  56303. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56304. */
  56305. function ConeParticleEmitter(radius, angle,
  56306. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56307. directionRandomizer) {
  56308. if (radius === void 0) { radius = 1; }
  56309. if (angle === void 0) { angle = Math.PI; }
  56310. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56311. this.directionRandomizer = directionRandomizer;
  56312. /**
  56313. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56314. */
  56315. this.radiusRange = 1;
  56316. /**
  56317. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56318. */
  56319. this.heightRange = 1;
  56320. this.angle = angle;
  56321. this.radius = radius;
  56322. }
  56323. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56324. /**
  56325. * Gets or sets the radius of the emission cone
  56326. */
  56327. get: function () {
  56328. return this._radius;
  56329. },
  56330. set: function (value) {
  56331. this._radius = value;
  56332. this._buildHeight();
  56333. },
  56334. enumerable: true,
  56335. configurable: true
  56336. });
  56337. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56338. /**
  56339. * Gets or sets the angle of the emission cone
  56340. */
  56341. get: function () {
  56342. return this._angle;
  56343. },
  56344. set: function (value) {
  56345. this._angle = value;
  56346. this._buildHeight();
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. ConeParticleEmitter.prototype._buildHeight = function () {
  56352. if (this._angle !== 0) {
  56353. this._height = this._radius / Math.tan(this._angle / 2);
  56354. }
  56355. else {
  56356. this._height = 1;
  56357. }
  56358. };
  56359. /**
  56360. * Called by the particle System when the direction is computed for the created particle.
  56361. * @param worldMatrix is the world matrix of the particle system
  56362. * @param directionToUpdate is the direction vector to update with the result
  56363. * @param particle is the particle we are computed the direction for
  56364. */
  56365. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56366. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56367. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56368. }
  56369. else {
  56370. // measure the direction Vector from the emitter to the particle.
  56371. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56372. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56373. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56374. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56375. direction.x += randX;
  56376. direction.y += randY;
  56377. direction.z += randZ;
  56378. direction.normalize();
  56379. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56380. }
  56381. };
  56382. /**
  56383. * Called by the particle System when the position is computed for the created particle.
  56384. * @param worldMatrix is the world matrix of the particle system
  56385. * @param positionToUpdate is the position vector to update with the result
  56386. * @param particle is the particle we are computed the position for
  56387. */
  56388. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56389. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56390. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56391. // Better distribution in a cone at normal angles.
  56392. h = 1 - h * h;
  56393. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56394. radius = radius * h;
  56395. var randX = radius * Math.sin(s);
  56396. var randZ = radius * Math.cos(s);
  56397. var randY = h * this._height;
  56398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56399. };
  56400. /**
  56401. * Clones the current emitter and returns a copy of it
  56402. * @returns the new emitter
  56403. */
  56404. ConeParticleEmitter.prototype.clone = function () {
  56405. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56406. BABYLON.Tools.DeepCopy(this, newOne);
  56407. return newOne;
  56408. };
  56409. /**
  56410. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56411. * @param effect defines the update shader
  56412. */
  56413. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56414. effect.setFloat2("radius", this._radius, this.radiusRange);
  56415. effect.setFloat("coneAngle", this._angle);
  56416. effect.setFloat2("height", this._height, this.heightRange);
  56417. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56418. };
  56419. /**
  56420. * Returns a string to use to update the GPU particles update shader
  56421. * @returns a string containng the defines string
  56422. */
  56423. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56424. return "#define CONEEMITTER";
  56425. };
  56426. /**
  56427. * Returns the string "ConeParticleEmitter"
  56428. * @returns a string containing the class name
  56429. */
  56430. ConeParticleEmitter.prototype.getClassName = function () {
  56431. return "ConeParticleEmitter";
  56432. };
  56433. /**
  56434. * Serializes the particle system to a JSON object.
  56435. * @returns the JSON object
  56436. */
  56437. ConeParticleEmitter.prototype.serialize = function () {
  56438. var serializationObject = {};
  56439. serializationObject.type = this.getClassName();
  56440. serializationObject.radius = this._radius;
  56441. serializationObject.angle = this._angle;
  56442. serializationObject.directionRandomizer = this.directionRandomizer;
  56443. return serializationObject;
  56444. };
  56445. /**
  56446. * Parse properties from a JSON object
  56447. * @param serializationObject defines the JSON object
  56448. */
  56449. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56450. this.radius = serializationObject.radius;
  56451. this.angle = serializationObject.angle;
  56452. this.directionRandomizer = serializationObject.directionRandomizer;
  56453. };
  56454. return ConeParticleEmitter;
  56455. }());
  56456. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56457. })(BABYLON || (BABYLON = {}));
  56458. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56459. var BABYLON;
  56460. (function (BABYLON) {
  56461. /**
  56462. * Particle emitter emitting particles from the inside of a sphere.
  56463. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56464. */
  56465. var SphereParticleEmitter = /** @class */ (function () {
  56466. /**
  56467. * Creates a new instance SphereParticleEmitter
  56468. * @param radius the radius of the emission sphere (1 by default)
  56469. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56470. */
  56471. function SphereParticleEmitter(
  56472. /**
  56473. * The radius of the emission sphere.
  56474. */
  56475. radius,
  56476. /**
  56477. * How much to randomize the particle direction [0-1].
  56478. */
  56479. directionRandomizer) {
  56480. if (radius === void 0) { radius = 1; }
  56481. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56482. this.radius = radius;
  56483. this.directionRandomizer = directionRandomizer;
  56484. /**
  56485. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56486. */
  56487. this.radiusRange = 1;
  56488. }
  56489. /**
  56490. * Called by the particle System when the direction is computed for the created particle.
  56491. * @param worldMatrix is the world matrix of the particle system
  56492. * @param directionToUpdate is the direction vector to update with the result
  56493. * @param particle is the particle we are computed the direction for
  56494. */
  56495. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56496. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56497. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56498. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56499. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56500. direction.x += randX;
  56501. direction.y += randY;
  56502. direction.z += randZ;
  56503. direction.normalize();
  56504. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56505. };
  56506. /**
  56507. * Called by the particle System when the position is computed for the created particle.
  56508. * @param worldMatrix is the world matrix of the particle system
  56509. * @param positionToUpdate is the position vector to update with the result
  56510. * @param particle is the particle we are computed the position for
  56511. */
  56512. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56513. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56514. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56515. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56516. var theta = Math.acos(2 * v - 1);
  56517. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56518. var randY = randRadius * Math.cos(theta);
  56519. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56521. };
  56522. /**
  56523. * Clones the current emitter and returns a copy of it
  56524. * @returns the new emitter
  56525. */
  56526. SphereParticleEmitter.prototype.clone = function () {
  56527. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56528. BABYLON.Tools.DeepCopy(this, newOne);
  56529. return newOne;
  56530. };
  56531. /**
  56532. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56533. * @param effect defines the update shader
  56534. */
  56535. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56536. effect.setFloat("radius", this.radius);
  56537. effect.setFloat("radiusRange", this.radiusRange);
  56538. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56539. };
  56540. /**
  56541. * Returns a string to use to update the GPU particles update shader
  56542. * @returns a string containng the defines string
  56543. */
  56544. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56545. return "#define SPHEREEMITTER";
  56546. };
  56547. /**
  56548. * Returns the string "SphereParticleEmitter"
  56549. * @returns a string containing the class name
  56550. */
  56551. SphereParticleEmitter.prototype.getClassName = function () {
  56552. return "SphereParticleEmitter";
  56553. };
  56554. /**
  56555. * Serializes the particle system to a JSON object.
  56556. * @returns the JSON object
  56557. */
  56558. SphereParticleEmitter.prototype.serialize = function () {
  56559. var serializationObject = {};
  56560. serializationObject.type = this.getClassName();
  56561. serializationObject.radius = this.radius;
  56562. serializationObject.radiusRange = this.radiusRange;
  56563. serializationObject.directionRandomizer = this.directionRandomizer;
  56564. return serializationObject;
  56565. };
  56566. /**
  56567. * Parse properties from a JSON object
  56568. * @param serializationObject defines the JSON object
  56569. */
  56570. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56571. this.radius = serializationObject.radius;
  56572. this.radiusRange = serializationObject.radiusRange;
  56573. this.directionRandomizer = serializationObject.directionRandomizer;
  56574. };
  56575. return SphereParticleEmitter;
  56576. }());
  56577. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56578. /**
  56579. * Particle emitter emitting particles from the inside of a sphere.
  56580. * It emits the particles randomly between two vectors.
  56581. */
  56582. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56583. __extends(SphereDirectedParticleEmitter, _super);
  56584. /**
  56585. * Creates a new instance SphereDirectedParticleEmitter
  56586. * @param radius the radius of the emission sphere (1 by default)
  56587. * @param direction1 the min limit of the emission direction (up vector by default)
  56588. * @param direction2 the max limit of the emission direction (up vector by default)
  56589. */
  56590. function SphereDirectedParticleEmitter(radius,
  56591. /**
  56592. * The min limit of the emission direction.
  56593. */
  56594. direction1,
  56595. /**
  56596. * The max limit of the emission direction.
  56597. */
  56598. direction2) {
  56599. if (radius === void 0) { radius = 1; }
  56600. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56601. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56602. var _this = _super.call(this, radius) || this;
  56603. _this.direction1 = direction1;
  56604. _this.direction2 = direction2;
  56605. return _this;
  56606. }
  56607. /**
  56608. * Called by the particle System when the direction is computed for the created particle.
  56609. * @param worldMatrix is the world matrix of the particle system
  56610. * @param directionToUpdate is the direction vector to update with the result
  56611. * @param particle is the particle we are computed the direction for
  56612. */
  56613. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56614. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56615. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56616. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56617. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56618. };
  56619. /**
  56620. * Clones the current emitter and returns a copy of it
  56621. * @returns the new emitter
  56622. */
  56623. SphereDirectedParticleEmitter.prototype.clone = function () {
  56624. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56625. BABYLON.Tools.DeepCopy(this, newOne);
  56626. return newOne;
  56627. };
  56628. /**
  56629. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56630. * @param effect defines the update shader
  56631. */
  56632. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56633. effect.setFloat("radius", this.radius);
  56634. effect.setFloat("radiusRange", this.radiusRange);
  56635. effect.setVector3("direction1", this.direction1);
  56636. effect.setVector3("direction2", this.direction2);
  56637. };
  56638. /**
  56639. * Returns a string to use to update the GPU particles update shader
  56640. * @returns a string containng the defines string
  56641. */
  56642. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56643. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56644. };
  56645. /**
  56646. * Returns the string "SphereDirectedParticleEmitter"
  56647. * @returns a string containing the class name
  56648. */
  56649. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56650. return "SphereDirectedParticleEmitter";
  56651. };
  56652. /**
  56653. * Serializes the particle system to a JSON object.
  56654. * @returns the JSON object
  56655. */
  56656. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56657. var serializationObject = _super.prototype.serialize.call(this);
  56658. serializationObject.direction1 = this.direction1.asArray();
  56659. serializationObject.direction2 = this.direction2.asArray();
  56660. return serializationObject;
  56661. };
  56662. /**
  56663. * Parse properties from a JSON object
  56664. * @param serializationObject defines the JSON object
  56665. */
  56666. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56667. _super.prototype.parse.call(this, serializationObject);
  56668. this.direction1.copyFrom(serializationObject.direction1);
  56669. this.direction2.copyFrom(serializationObject.direction2);
  56670. };
  56671. return SphereDirectedParticleEmitter;
  56672. }(SphereParticleEmitter));
  56673. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56674. })(BABYLON || (BABYLON = {}));
  56675. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56676. var BABYLON;
  56677. (function (BABYLON) {
  56678. // Adds the parsers to the scene parsers.
  56679. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  56680. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  56681. if (!individualParser) {
  56682. return;
  56683. }
  56684. // Particles Systems
  56685. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56686. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56687. var parsedParticleSystem = parsedData.particleSystems[index];
  56688. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  56689. }
  56690. }
  56691. });
  56692. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  56693. if (parsedParticleSystem.activeParticleCount) {
  56694. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56695. return ps;
  56696. }
  56697. else {
  56698. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56699. return ps;
  56700. }
  56701. });
  56702. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  56703. if (uniformsNames === void 0) { uniformsNames = []; }
  56704. if (samplers === void 0) { samplers = []; }
  56705. if (defines === void 0) { defines = ""; }
  56706. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  56707. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  56708. if (defines.indexOf(" BILLBOARD") === -1) {
  56709. defines += "\n#define BILLBOARD\n";
  56710. }
  56711. if (samplers.indexOf("diffuseSampler") === -1) {
  56712. samplers.push("diffuseSampler");
  56713. }
  56714. return this.createEffect({
  56715. vertex: "particles",
  56716. fragmentElement: fragmentName
  56717. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  56718. };
  56719. })(BABYLON || (BABYLON = {}));
  56720. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  56721. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56722. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56723. s = arguments[i];
  56724. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56725. t[p] = s[p];
  56726. }
  56727. return t;
  56728. };
  56729. var BABYLON;
  56730. (function (BABYLON) {
  56731. /**
  56732. * This represents a GPU particle system in Babylon
  56733. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56734. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56735. */
  56736. var GPUParticleSystem = /** @class */ (function () {
  56737. /**
  56738. * Instantiates a GPU particle system.
  56739. * 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.
  56740. * @param name The name of the particle system
  56741. * @param options The options used to create the system
  56742. * @param scene The scene the particle system belongs to
  56743. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56744. */
  56745. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  56746. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56747. /**
  56748. * The emitter represents the Mesh or position we are attaching the particle system to.
  56749. */
  56750. this.emitter = null;
  56751. /**
  56752. * The rendering group used by the Particle system to chose when to render.
  56753. */
  56754. this.renderingGroupId = 0;
  56755. /**
  56756. * The layer mask we are rendering the particles through.
  56757. */
  56758. this.layerMask = 0x0FFFFFFF;
  56759. this._accumulatedCount = 0;
  56760. this._targetIndex = 0;
  56761. this._currentRenderId = -1;
  56762. this._started = false;
  56763. this._stopped = false;
  56764. this._timeDelta = 0;
  56765. this._attributesStrideSize = 21;
  56766. this._actualFrame = 0;
  56767. this._rawTextureWidth = 256;
  56768. /**
  56769. * List of animations used by the particle system.
  56770. */
  56771. this.animations = [];
  56772. /**
  56773. * An event triggered when the system is disposed.
  56774. */
  56775. this.onDisposeObservable = new BABYLON.Observable();
  56776. /**
  56777. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56778. */
  56779. this.updateSpeed = 0.01;
  56780. /**
  56781. * The amount of time the particle system is running (depends of the overall update speed).
  56782. */
  56783. this.targetStopDuration = 0;
  56784. /**
  56785. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56786. */
  56787. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56788. /**
  56789. * Minimum life time of emitting particles.
  56790. */
  56791. this.minLifeTime = 1;
  56792. /**
  56793. * Maximum life time of emitting particles.
  56794. */
  56795. this.maxLifeTime = 1;
  56796. /**
  56797. * Minimum Size of emitting particles.
  56798. */
  56799. this.minSize = 1;
  56800. /**
  56801. * Maximum Size of emitting particles.
  56802. */
  56803. this.maxSize = 1;
  56804. /**
  56805. * Minimum scale of emitting particles on X axis.
  56806. */
  56807. this.minScaleX = 1;
  56808. /**
  56809. * Maximum scale of emitting particles on X axis.
  56810. */
  56811. this.maxScaleX = 1;
  56812. /**
  56813. * Minimum scale of emitting particles on Y axis.
  56814. */
  56815. this.minScaleY = 1;
  56816. /**
  56817. * Maximum scale of emitting particles on Y axis.
  56818. */
  56819. this.maxScaleY = 1;
  56820. /**
  56821. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56822. */
  56823. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56824. /**
  56825. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56826. */
  56827. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56828. /**
  56829. * Color the particle will have at the end of its lifetime.
  56830. */
  56831. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56832. /**
  56833. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56834. */
  56835. this.emitRate = 100;
  56836. /**
  56837. * You can use gravity if you want to give an orientation to your particles.
  56838. */
  56839. this.gravity = BABYLON.Vector3.Zero();
  56840. /**
  56841. * Minimum power of emitting particles.
  56842. */
  56843. this.minEmitPower = 1;
  56844. /**
  56845. * Maximum power of emitting particles.
  56846. */
  56847. this.maxEmitPower = 1;
  56848. /**
  56849. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56850. */
  56851. this.minAngularSpeed = 0;
  56852. /**
  56853. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56854. */
  56855. this.maxAngularSpeed = 0;
  56856. /**
  56857. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56858. * to override the particles.
  56859. */
  56860. this.forceDepthWrite = false;
  56861. this._preWarmDone = false;
  56862. /** 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 */
  56863. this.preWarmCycles = 0;
  56864. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56865. this.preWarmStepOffset = 1;
  56866. /**
  56867. * Gets or sets the minimal initial rotation in radians.
  56868. */
  56869. this.minInitialRotation = 0;
  56870. /**
  56871. * Gets or sets the maximal initial rotation in radians.
  56872. */
  56873. this.maxInitialRotation = 0;
  56874. /**
  56875. * 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)
  56876. */
  56877. this.spriteCellChangeSpeed = 1;
  56878. /**
  56879. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56880. */
  56881. this.startSpriteCellID = 0;
  56882. /**
  56883. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56884. */
  56885. this.endSpriteCellID = 0;
  56886. /**
  56887. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56888. */
  56889. this.spriteCellWidth = 0;
  56890. /**
  56891. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56892. */
  56893. this.spriteCellHeight = 0;
  56894. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56895. this.translationPivot = new BABYLON.Vector2(0, 0);
  56896. /**
  56897. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56898. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  56899. */
  56900. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56901. this._isBillboardBased = true;
  56902. this._colorGradients = null;
  56903. this._angularSpeedGradients = null;
  56904. this._sizeGradients = null;
  56905. this._velocityGradients = null;
  56906. this.id = name;
  56907. this.name = name;
  56908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56909. this._engine = this._scene.getEngine();
  56910. if (!options.randomTextureSize) {
  56911. delete options.randomTextureSize;
  56912. }
  56913. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56914. var optionsAsNumber = options;
  56915. if (isFinite(optionsAsNumber)) {
  56916. fullOptions.capacity = optionsAsNumber;
  56917. }
  56918. this._capacity = fullOptions.capacity;
  56919. this._activeCount = fullOptions.capacity;
  56920. this._currentActiveCount = 0;
  56921. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56922. this._scene.particleSystems.push(this);
  56923. this._updateEffectOptions = {
  56924. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  56925. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56926. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56927. "angleRange", "radiusRange", "cellInfos"],
  56928. uniformBuffersNames: [],
  56929. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  56930. defines: "",
  56931. fallbacks: null,
  56932. onCompiled: null,
  56933. onError: null,
  56934. indexParameters: null,
  56935. maxSimultaneousLights: 0,
  56936. transformFeedbackVaryings: []
  56937. };
  56938. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56939. // Random data
  56940. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56941. var d = [];
  56942. for (var i = 0; i < maxTextureSize; ++i) {
  56943. d.push(Math.random());
  56944. d.push(Math.random());
  56945. d.push(Math.random());
  56946. d.push(Math.random());
  56947. }
  56948. 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);
  56949. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56950. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56951. d = [];
  56952. for (var i = 0; i < maxTextureSize; ++i) {
  56953. d.push(Math.random());
  56954. d.push(Math.random());
  56955. d.push(Math.random());
  56956. d.push(Math.random());
  56957. }
  56958. 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);
  56959. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56960. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56961. this._randomTextureSize = maxTextureSize;
  56962. }
  56963. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56964. /**
  56965. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56966. */
  56967. get: function () {
  56968. if (!BABYLON.Engine.LastCreatedEngine) {
  56969. return false;
  56970. }
  56971. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56972. },
  56973. enumerable: true,
  56974. configurable: true
  56975. });
  56976. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56977. /**
  56978. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56979. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56980. */
  56981. get: function () {
  56982. if (this.particleEmitterType.direction1) {
  56983. return this.particleEmitterType.direction1;
  56984. }
  56985. return BABYLON.Vector3.Zero();
  56986. },
  56987. set: function (value) {
  56988. if (this.particleEmitterType.direction1) {
  56989. this.particleEmitterType.direction1 = value;
  56990. }
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56996. /**
  56997. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56998. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56999. */
  57000. get: function () {
  57001. if (this.particleEmitterType.direction2) {
  57002. return this.particleEmitterType.direction2;
  57003. }
  57004. return BABYLON.Vector3.Zero();
  57005. },
  57006. set: function (value) {
  57007. if (this.particleEmitterType.direction2) {
  57008. this.particleEmitterType.direction2 = value;
  57009. }
  57010. },
  57011. enumerable: true,
  57012. configurable: true
  57013. });
  57014. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57015. /**
  57016. * 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.
  57017. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57018. */
  57019. get: function () {
  57020. if (this.particleEmitterType.minEmitBox) {
  57021. return this.particleEmitterType.minEmitBox;
  57022. }
  57023. return BABYLON.Vector3.Zero();
  57024. },
  57025. set: function (value) {
  57026. if (this.particleEmitterType.minEmitBox) {
  57027. this.particleEmitterType.minEmitBox = value;
  57028. }
  57029. },
  57030. enumerable: true,
  57031. configurable: true
  57032. });
  57033. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57034. /**
  57035. * 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.
  57036. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57037. */
  57038. get: function () {
  57039. if (this.particleEmitterType.maxEmitBox) {
  57040. return this.particleEmitterType.maxEmitBox;
  57041. }
  57042. return BABYLON.Vector3.Zero();
  57043. },
  57044. set: function (value) {
  57045. if (this.particleEmitterType.maxEmitBox) {
  57046. this.particleEmitterType.maxEmitBox = value;
  57047. }
  57048. },
  57049. enumerable: true,
  57050. configurable: true
  57051. });
  57052. /**
  57053. * Gets the maximum number of particles active at the same time.
  57054. * @returns The max number of active particles.
  57055. */
  57056. GPUParticleSystem.prototype.getCapacity = function () {
  57057. return this._capacity;
  57058. };
  57059. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57060. /**
  57061. * Gets or set the number of active particles
  57062. */
  57063. get: function () {
  57064. return this._activeCount;
  57065. },
  57066. set: function (value) {
  57067. this._activeCount = Math.min(value, this._capacity);
  57068. },
  57069. enumerable: true,
  57070. configurable: true
  57071. });
  57072. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57073. /**
  57074. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57075. */
  57076. get: function () {
  57077. return this._isAnimationSheetEnabled;
  57078. },
  57079. enumerable: true,
  57080. configurable: true
  57081. });
  57082. /**
  57083. * Is this system ready to be used/rendered
  57084. * @return true if the system is ready
  57085. */
  57086. GPUParticleSystem.prototype.isReady = function () {
  57087. if (!this._updateEffect) {
  57088. this._recreateUpdateEffect();
  57089. this._recreateRenderEffect();
  57090. return false;
  57091. }
  57092. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57093. return false;
  57094. }
  57095. return true;
  57096. };
  57097. /**
  57098. * Gets Wether the system has been started.
  57099. * @returns True if it has been started, otherwise false.
  57100. */
  57101. GPUParticleSystem.prototype.isStarted = function () {
  57102. return this._started;
  57103. };
  57104. /**
  57105. * Starts the particle system and begins to emit.
  57106. */
  57107. GPUParticleSystem.prototype.start = function () {
  57108. this._started = true;
  57109. this._stopped = false;
  57110. this._preWarmDone = false;
  57111. };
  57112. /**
  57113. * Stops the particle system.
  57114. */
  57115. GPUParticleSystem.prototype.stop = function () {
  57116. this._stopped = true;
  57117. };
  57118. /**
  57119. * Remove all active particles
  57120. */
  57121. GPUParticleSystem.prototype.reset = function () {
  57122. this._releaseBuffers();
  57123. this._releaseVAOs();
  57124. this._currentActiveCount = 0;
  57125. this._targetIndex = 0;
  57126. };
  57127. /**
  57128. * Returns the string "GPUParticleSystem"
  57129. * @returns a string containing the class name
  57130. */
  57131. GPUParticleSystem.prototype.getClassName = function () {
  57132. return "GPUParticleSystem";
  57133. };
  57134. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57135. /**
  57136. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57137. */
  57138. get: function () {
  57139. return this._isBillboardBased;
  57140. },
  57141. set: function (value) {
  57142. if (this._isBillboardBased === value) {
  57143. return;
  57144. }
  57145. this._isBillboardBased = value;
  57146. this._releaseBuffers();
  57147. },
  57148. enumerable: true,
  57149. configurable: true
  57150. });
  57151. /**
  57152. * Gets the current list of color gradients.
  57153. * You must use addColorGradient and removeColorGradient to udpate this list
  57154. * @returns the list of color gradients
  57155. */
  57156. GPUParticleSystem.prototype.getColorGradients = function () {
  57157. return this._colorGradients;
  57158. };
  57159. /**
  57160. * Gets the current list of size gradients.
  57161. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57162. * @returns the list of size gradients
  57163. */
  57164. GPUParticleSystem.prototype.getSizeGradients = function () {
  57165. return this._sizeGradients;
  57166. };
  57167. /**
  57168. * Gets the current list of angular speed gradients.
  57169. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57170. * @returns the list of angular speed gradients
  57171. */
  57172. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57173. return this._angularSpeedGradients;
  57174. };
  57175. /**
  57176. * Gets the current list of velocity gradients.
  57177. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57178. * @returns the list of angular speed gradients
  57179. */
  57180. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57181. return this._velocityGradients;
  57182. };
  57183. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57184. if (!gradients) {
  57185. return this;
  57186. }
  57187. var index = 0;
  57188. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57189. var valueGradient = gradients_1[_i];
  57190. if (valueGradient.gradient === gradient) {
  57191. gradients.splice(index, 1);
  57192. break;
  57193. }
  57194. index++;
  57195. }
  57196. if (texture) {
  57197. texture.dispose();
  57198. }
  57199. this._releaseBuffers();
  57200. return this;
  57201. };
  57202. /**
  57203. * Adds a new color gradient
  57204. * @param gradient defines the gradient to use (between 0 and 1)
  57205. * @param color defines the color to affect to the specified gradient
  57206. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57207. * @returns the current particle system
  57208. */
  57209. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57210. if (!this._colorGradients) {
  57211. this._colorGradients = [];
  57212. }
  57213. var colorGradient = new BABYLON.ColorGradient();
  57214. colorGradient.gradient = gradient;
  57215. colorGradient.color1 = color1;
  57216. this._colorGradients.push(colorGradient);
  57217. this._colorGradients.sort(function (a, b) {
  57218. if (a.gradient < b.gradient) {
  57219. return -1;
  57220. }
  57221. else if (a.gradient > b.gradient) {
  57222. return 1;
  57223. }
  57224. return 0;
  57225. });
  57226. if (this._colorGradientsTexture) {
  57227. this._colorGradientsTexture.dispose();
  57228. this._colorGradientsTexture = null;
  57229. }
  57230. this._releaseBuffers();
  57231. return this;
  57232. };
  57233. /**
  57234. * Remove a specific color gradient
  57235. * @param gradient defines the gradient to remove
  57236. * @returns the current particle system
  57237. */
  57238. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57239. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57240. this._colorGradientsTexture = null;
  57241. return this;
  57242. };
  57243. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57244. var valueGradient = new BABYLON.FactorGradient();
  57245. valueGradient.gradient = gradient;
  57246. valueGradient.factor1 = factor;
  57247. factorGradients.push(valueGradient);
  57248. factorGradients.sort(function (a, b) {
  57249. if (a.gradient < b.gradient) {
  57250. return -1;
  57251. }
  57252. else if (a.gradient > b.gradient) {
  57253. return 1;
  57254. }
  57255. return 0;
  57256. });
  57257. this._releaseBuffers();
  57258. };
  57259. /**
  57260. * Adds a new size gradient
  57261. * @param gradient defines the gradient to use (between 0 and 1)
  57262. * @param factor defines the size factor to affect to the specified gradient
  57263. * @returns the current particle system
  57264. */
  57265. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57266. if (!this._sizeGradients) {
  57267. this._sizeGradients = [];
  57268. }
  57269. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57270. if (this._sizeGradientsTexture) {
  57271. this._sizeGradientsTexture.dispose();
  57272. this._sizeGradientsTexture = null;
  57273. }
  57274. this._releaseBuffers();
  57275. return this;
  57276. };
  57277. /**
  57278. * Remove a specific size gradient
  57279. * @param gradient defines the gradient to remove
  57280. * @returns the current particle system
  57281. */
  57282. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57283. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57284. this._sizeGradientsTexture = null;
  57285. return this;
  57286. };
  57287. /**
  57288. * Adds a new angular speed gradient
  57289. * @param gradient defines the gradient to use (between 0 and 1)
  57290. * @param factor defines the size factor to affect to the specified gradient
  57291. * @returns the current particle system
  57292. */
  57293. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57294. if (!this._angularSpeedGradients) {
  57295. this._angularSpeedGradients = [];
  57296. }
  57297. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57298. if (this._angularSpeedGradientsTexture) {
  57299. this._angularSpeedGradientsTexture.dispose();
  57300. this._angularSpeedGradientsTexture = null;
  57301. }
  57302. this._releaseBuffers();
  57303. return this;
  57304. };
  57305. /**
  57306. * Remove a specific angular speed gradient
  57307. * @param gradient defines the gradient to remove
  57308. * @returns the current particle system
  57309. */
  57310. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57311. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57312. this._angularSpeedGradientsTexture = null;
  57313. return this;
  57314. };
  57315. /**
  57316. * Adds a new velocity gradient
  57317. * @param gradient defines the gradient to use (between 0 and 1)
  57318. * @param factor defines the size factor to affect to the specified gradient
  57319. * @returns the current particle system
  57320. */
  57321. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57322. if (!this._velocityGradients) {
  57323. this._velocityGradients = [];
  57324. }
  57325. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57326. if (this._velocityGradientsTexture) {
  57327. this._velocityGradientsTexture.dispose();
  57328. this._velocityGradientsTexture = null;
  57329. }
  57330. this._releaseBuffers();
  57331. return this;
  57332. };
  57333. /**
  57334. * Remove a specific velocity gradient
  57335. * @param gradient defines the gradient to remove
  57336. * @returns the current particle system
  57337. */
  57338. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57339. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57340. this._velocityGradientsTexture = null;
  57341. return this;
  57342. };
  57343. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57344. var updateVertexBuffers = {};
  57345. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57346. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57347. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57348. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57349. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57350. var offset = 12;
  57351. if (!this._colorGradientsTexture) {
  57352. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57353. offset += 4;
  57354. }
  57355. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57356. offset += 3;
  57357. if (!this._isBillboardBased) {
  57358. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57359. offset += 3;
  57360. }
  57361. if (this._angularSpeedGradientsTexture) {
  57362. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57363. offset += 1;
  57364. }
  57365. else {
  57366. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57367. offset += 2;
  57368. }
  57369. if (this._isAnimationSheetEnabled) {
  57370. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57371. offset += 1;
  57372. }
  57373. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57374. this._engine.bindArrayBuffer(null);
  57375. return vao;
  57376. };
  57377. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57378. var renderVertexBuffers = {};
  57379. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57380. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57381. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57382. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57383. var offset = 12;
  57384. if (!this._colorGradientsTexture) {
  57385. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57386. offset += 4;
  57387. }
  57388. offset += 3; // Direction
  57389. if (!this._isBillboardBased) {
  57390. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57391. offset += 3;
  57392. }
  57393. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57394. if (this._angularSpeedGradientsTexture) {
  57395. offset++;
  57396. }
  57397. else {
  57398. offset += 2;
  57399. }
  57400. if (this._isAnimationSheetEnabled) {
  57401. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57402. offset += 1;
  57403. }
  57404. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57405. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57406. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57407. this._engine.bindArrayBuffer(null);
  57408. return vao;
  57409. };
  57410. GPUParticleSystem.prototype._initialize = function (force) {
  57411. if (force === void 0) { force = false; }
  57412. if (this._buffer0 && !force) {
  57413. return;
  57414. }
  57415. var engine = this._scene.getEngine();
  57416. var data = new Array();
  57417. if (!this.isBillboardBased) {
  57418. this._attributesStrideSize += 3;
  57419. }
  57420. if (this._colorGradientsTexture) {
  57421. this._attributesStrideSize -= 4;
  57422. }
  57423. if (this._angularSpeedGradientsTexture) {
  57424. this._attributesStrideSize -= 1;
  57425. }
  57426. if (this._isAnimationSheetEnabled) {
  57427. this._attributesStrideSize += 1;
  57428. }
  57429. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57430. // position
  57431. data.push(0.0);
  57432. data.push(0.0);
  57433. data.push(0.0);
  57434. // Age and life
  57435. data.push(0.0); // create the particle as a dead one to create a new one at start
  57436. data.push(0.0);
  57437. // Seed
  57438. data.push(Math.random());
  57439. data.push(Math.random());
  57440. data.push(Math.random());
  57441. data.push(Math.random());
  57442. // Size
  57443. data.push(0.0);
  57444. data.push(0.0);
  57445. data.push(0.0);
  57446. if (!this._colorGradientsTexture) {
  57447. // color
  57448. data.push(0.0);
  57449. data.push(0.0);
  57450. data.push(0.0);
  57451. data.push(0.0);
  57452. }
  57453. // direction
  57454. data.push(0.0);
  57455. data.push(0.0);
  57456. data.push(0.0);
  57457. if (!this.isBillboardBased) {
  57458. // initialDirection
  57459. data.push(0.0);
  57460. data.push(0.0);
  57461. data.push(0.0);
  57462. }
  57463. // angle
  57464. data.push(0.0);
  57465. if (!this._angularSpeedGradientsTexture) {
  57466. data.push(0.0);
  57467. }
  57468. if (this._isAnimationSheetEnabled) {
  57469. data.push(0.0);
  57470. }
  57471. }
  57472. // Sprite data
  57473. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57474. -0.5, 0.5, 0, 1,
  57475. -0.5, -0.5, 0, 0,
  57476. 0.5, -0.5, 1, 0]);
  57477. // Buffers
  57478. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57479. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57480. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57481. // Update VAO
  57482. this._updateVAO = [];
  57483. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57484. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57485. // Render VAO
  57486. this._renderVAO = [];
  57487. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57488. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57489. // Links
  57490. this._sourceBuffer = this._buffer0;
  57491. this._targetBuffer = this._buffer1;
  57492. };
  57493. /** @hidden */
  57494. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57495. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57496. if (this._isBillboardBased) {
  57497. defines += "\n#define BILLBOARD";
  57498. }
  57499. if (this._colorGradientsTexture) {
  57500. defines += "\n#define COLORGRADIENTS";
  57501. }
  57502. if (this._sizeGradientsTexture) {
  57503. defines += "\n#define SIZEGRADIENTS";
  57504. }
  57505. if (this._angularSpeedGradientsTexture) {
  57506. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57507. }
  57508. if (this._velocityGradientsTexture) {
  57509. defines += "\n#define VELOCITYGRADIENTS";
  57510. }
  57511. if (this.isAnimationSheetEnabled) {
  57512. defines += "\n#define ANIMATESHEET";
  57513. }
  57514. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57515. return;
  57516. }
  57517. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57518. if (!this._colorGradientsTexture) {
  57519. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57520. }
  57521. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57522. if (!this._isBillboardBased) {
  57523. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57524. }
  57525. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57526. if (this.isAnimationSheetEnabled) {
  57527. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57528. }
  57529. this._updateEffectOptions.defines = defines;
  57530. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57531. };
  57532. /** @hidden */
  57533. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57534. var defines = "";
  57535. if (this._scene.clipPlane) {
  57536. defines = "\n#define CLIPPLANE";
  57537. }
  57538. if (this._isBillboardBased) {
  57539. defines += "\n#define BILLBOARD";
  57540. switch (this.billboardMode) {
  57541. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57542. defines += "\n#define BILLBOARDY";
  57543. break;
  57544. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57545. default:
  57546. break;
  57547. }
  57548. }
  57549. if (this._colorGradientsTexture) {
  57550. defines += "\n#define COLORGRADIENTS";
  57551. }
  57552. if (this.isAnimationSheetEnabled) {
  57553. defines += "\n#define ANIMATESHEET";
  57554. }
  57555. if (this._renderEffect && this._renderEffect.defines === defines) {
  57556. return;
  57557. }
  57558. 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);
  57559. };
  57560. /**
  57561. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57562. * @param preWarm defines if we are in the pre-warmimg phase
  57563. */
  57564. GPUParticleSystem.prototype.animate = function (preWarm) {
  57565. if (preWarm === void 0) { preWarm = false; }
  57566. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57567. this._actualFrame += this._timeDelta;
  57568. if (!this._stopped) {
  57569. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57570. this.stop();
  57571. }
  57572. }
  57573. };
  57574. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57575. var texture = this[textureName];
  57576. if (!factorGradients || !factorGradients.length || texture) {
  57577. return;
  57578. }
  57579. var data = new Float32Array(this._rawTextureWidth);
  57580. for (var x = 0; x < this._rawTextureWidth; x++) {
  57581. var ratio = x / this._rawTextureWidth;
  57582. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57583. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57584. });
  57585. }
  57586. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57587. };
  57588. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57589. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57590. };
  57591. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57592. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57593. };
  57594. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  57595. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  57596. };
  57597. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57598. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57599. return;
  57600. }
  57601. var data = new Uint8Array(this._rawTextureWidth * 4);
  57602. var tmpColor = BABYLON.Tmp.Color4[0];
  57603. for (var x = 0; x < this._rawTextureWidth; x++) {
  57604. var ratio = x / this._rawTextureWidth;
  57605. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57606. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57607. data[x * 4] = tmpColor.r * 255;
  57608. data[x * 4 + 1] = tmpColor.g * 255;
  57609. data[x * 4 + 2] = tmpColor.b * 255;
  57610. data[x * 4 + 3] = tmpColor.a * 255;
  57611. });
  57612. }
  57613. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57614. };
  57615. /**
  57616. * Renders the particle system in its current state
  57617. * @param preWarm defines if the system should only update the particles but not render them
  57618. * @returns the current number of particles
  57619. */
  57620. GPUParticleSystem.prototype.render = function (preWarm) {
  57621. if (preWarm === void 0) { preWarm = false; }
  57622. if (!this._started) {
  57623. return 0;
  57624. }
  57625. this._createColorGradientTexture();
  57626. this._createSizeGradientTexture();
  57627. this._createAngularSpeedGradientTexture();
  57628. this._createVelocityGradientTexture();
  57629. this._recreateUpdateEffect();
  57630. this._recreateRenderEffect();
  57631. if (!this.isReady()) {
  57632. return 0;
  57633. }
  57634. if (!preWarm) {
  57635. if (!this._preWarmDone && this.preWarmCycles) {
  57636. for (var index = 0; index < this.preWarmCycles; index++) {
  57637. this.animate(true);
  57638. this.render(true);
  57639. }
  57640. this._preWarmDone = true;
  57641. }
  57642. if (this._currentRenderId === this._scene.getRenderId()) {
  57643. return 0;
  57644. }
  57645. this._currentRenderId = this._scene.getRenderId();
  57646. }
  57647. // Get everything ready to render
  57648. this._initialize();
  57649. this._accumulatedCount += this.emitRate * this._timeDelta;
  57650. if (this._accumulatedCount > 1) {
  57651. var intPart = this._accumulatedCount | 0;
  57652. this._accumulatedCount -= intPart;
  57653. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57654. }
  57655. if (!this._currentActiveCount) {
  57656. return 0;
  57657. }
  57658. // Enable update effect
  57659. this._engine.enableEffect(this._updateEffect);
  57660. this._engine.setState(false);
  57661. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57662. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57663. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57664. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57665. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57666. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57667. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57668. if (!this._colorGradientsTexture) {
  57669. this._updateEffect.setDirectColor4("color1", this.color1);
  57670. this._updateEffect.setDirectColor4("color2", this.color2);
  57671. }
  57672. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57673. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57674. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57675. this._updateEffect.setVector3("gravity", this.gravity);
  57676. if (this._sizeGradientsTexture) {
  57677. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57678. }
  57679. if (this._angularSpeedGradientsTexture) {
  57680. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  57681. }
  57682. if (this._velocityGradientsTexture) {
  57683. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  57684. }
  57685. if (this.particleEmitterType) {
  57686. this.particleEmitterType.applyToShader(this._updateEffect);
  57687. }
  57688. if (this._isAnimationSheetEnabled) {
  57689. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57690. }
  57691. var emitterWM;
  57692. if (this.emitter.position) {
  57693. var emitterMesh = this.emitter;
  57694. emitterWM = emitterMesh.getWorldMatrix();
  57695. }
  57696. else {
  57697. var emitterPosition = this.emitter;
  57698. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57699. }
  57700. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57701. // Bind source VAO
  57702. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57703. // Update
  57704. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57705. this._engine.setRasterizerState(false);
  57706. this._engine.beginTransformFeedback();
  57707. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57708. this._engine.endTransformFeedback();
  57709. this._engine.setRasterizerState(true);
  57710. this._engine.bindTransformFeedbackBuffer(null);
  57711. if (!preWarm) {
  57712. // Enable render effect
  57713. this._engine.enableEffect(this._renderEffect);
  57714. var viewMatrix = this._scene.getViewMatrix();
  57715. this._renderEffect.setMatrix("view", viewMatrix);
  57716. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57717. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57718. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57719. if (this._colorGradientsTexture) {
  57720. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57721. }
  57722. else {
  57723. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57724. }
  57725. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57726. var baseSize = this.particleTexture.getBaseSize();
  57727. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57728. }
  57729. if (this._isBillboardBased) {
  57730. var camera = this._scene.activeCamera;
  57731. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57732. }
  57733. if (this._scene.clipPlane) {
  57734. var clipPlane = this._scene.clipPlane;
  57735. var invView = viewMatrix.clone();
  57736. invView.invert();
  57737. this._renderEffect.setMatrix("invView", invView);
  57738. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57739. }
  57740. // Draw order
  57741. switch (this.blendMode) {
  57742. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57743. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57744. break;
  57745. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57746. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57747. break;
  57748. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57749. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57750. break;
  57751. }
  57752. if (this.forceDepthWrite) {
  57753. this._engine.setDepthWrite(true);
  57754. }
  57755. // Bind source VAO
  57756. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57757. // Render
  57758. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57759. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57760. }
  57761. // Switch VAOs
  57762. this._targetIndex++;
  57763. if (this._targetIndex === 2) {
  57764. this._targetIndex = 0;
  57765. }
  57766. // Switch buffers
  57767. var tmpBuffer = this._sourceBuffer;
  57768. this._sourceBuffer = this._targetBuffer;
  57769. this._targetBuffer = tmpBuffer;
  57770. return this._currentActiveCount;
  57771. };
  57772. /**
  57773. * Rebuilds the particle system
  57774. */
  57775. GPUParticleSystem.prototype.rebuild = function () {
  57776. this._initialize(true);
  57777. };
  57778. GPUParticleSystem.prototype._releaseBuffers = function () {
  57779. if (this._buffer0) {
  57780. this._buffer0.dispose();
  57781. this._buffer0 = null;
  57782. }
  57783. if (this._buffer1) {
  57784. this._buffer1.dispose();
  57785. this._buffer1 = null;
  57786. }
  57787. if (this._spriteBuffer) {
  57788. this._spriteBuffer.dispose();
  57789. this._spriteBuffer = null;
  57790. }
  57791. };
  57792. GPUParticleSystem.prototype._releaseVAOs = function () {
  57793. if (!this._updateVAO) {
  57794. return;
  57795. }
  57796. for (var index = 0; index < this._updateVAO.length; index++) {
  57797. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57798. }
  57799. this._updateVAO = [];
  57800. for (var index = 0; index < this._renderVAO.length; index++) {
  57801. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57802. }
  57803. this._renderVAO = [];
  57804. };
  57805. /**
  57806. * Disposes the particle system and free the associated resources
  57807. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57808. */
  57809. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57810. if (disposeTexture === void 0) { disposeTexture = true; }
  57811. var index = this._scene.particleSystems.indexOf(this);
  57812. if (index > -1) {
  57813. this._scene.particleSystems.splice(index, 1);
  57814. }
  57815. this._releaseBuffers();
  57816. this._releaseVAOs();
  57817. if (this._colorGradientsTexture) {
  57818. this._colorGradientsTexture.dispose();
  57819. this._colorGradientsTexture = null;
  57820. }
  57821. if (this._sizeGradientsTexture) {
  57822. this._sizeGradientsTexture.dispose();
  57823. this._sizeGradientsTexture = null;
  57824. }
  57825. if (this._angularSpeedGradientsTexture) {
  57826. this._angularSpeedGradientsTexture.dispose();
  57827. this._angularSpeedGradientsTexture = null;
  57828. }
  57829. if (this._velocityGradientsTexture) {
  57830. this._velocityGradientsTexture.dispose();
  57831. this._velocityGradientsTexture = null;
  57832. }
  57833. if (this._randomTexture) {
  57834. this._randomTexture.dispose();
  57835. this._randomTexture = null;
  57836. }
  57837. if (this._randomTexture2) {
  57838. this._randomTexture2.dispose();
  57839. this._randomTexture2 = null;
  57840. }
  57841. if (disposeTexture && this.particleTexture) {
  57842. this.particleTexture.dispose();
  57843. this.particleTexture = null;
  57844. }
  57845. // Callback
  57846. this.onDisposeObservable.notifyObservers(this);
  57847. this.onDisposeObservable.clear();
  57848. };
  57849. /**
  57850. * Clones the particle system.
  57851. * @param name The name of the cloned object
  57852. * @param newEmitter The new emitter to use
  57853. * @returns the cloned particle system
  57854. */
  57855. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57856. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57857. BABYLON.Tools.DeepCopy(this, result);
  57858. if (newEmitter === undefined) {
  57859. newEmitter = this.emitter;
  57860. }
  57861. result.emitter = newEmitter;
  57862. if (this.particleTexture) {
  57863. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57864. }
  57865. return result;
  57866. };
  57867. /**
  57868. * Serializes the particle system to a JSON object.
  57869. * @returns the JSON object
  57870. */
  57871. GPUParticleSystem.prototype.serialize = function () {
  57872. var serializationObject = {};
  57873. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57874. serializationObject.activeParticleCount = this.activeParticleCount;
  57875. return serializationObject;
  57876. };
  57877. /**
  57878. * Parses a JSON object to create a GPU particle system.
  57879. * @param parsedParticleSystem The JSON object to parse
  57880. * @param scene The scene to create the particle system in
  57881. * @param rootUrl The root url to use to load external dependencies like texture
  57882. * @returns the parsed GPU particle system
  57883. */
  57884. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57885. var name = parsedParticleSystem.name;
  57886. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57887. if (parsedParticleSystem.activeParticleCount) {
  57888. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57889. }
  57890. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57891. return particleSystem;
  57892. };
  57893. return GPUParticleSystem;
  57894. }());
  57895. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57896. })(BABYLON || (BABYLON = {}));
  57897. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57898. var BABYLON;
  57899. (function (BABYLON) {
  57900. /**
  57901. * Represents one particle of a solid particle system.
  57902. */
  57903. var SolidParticle = /** @class */ (function () {
  57904. /**
  57905. * Creates a Solid Particle object.
  57906. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57907. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57908. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57909. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57910. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57911. * @param shapeId (integer) is the model shape identifier in the SPS.
  57912. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57913. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57914. */
  57915. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57916. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57917. /**
  57918. * particle global index
  57919. */
  57920. this.idx = 0;
  57921. /**
  57922. * The color of the particle
  57923. */
  57924. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57925. /**
  57926. * The world space position of the particle.
  57927. */
  57928. this.position = BABYLON.Vector3.Zero();
  57929. /**
  57930. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57931. */
  57932. this.rotation = BABYLON.Vector3.Zero();
  57933. /**
  57934. * The scaling of the particle.
  57935. */
  57936. this.scaling = BABYLON.Vector3.One();
  57937. /**
  57938. * The uvs of the particle.
  57939. */
  57940. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57941. /**
  57942. * The current speed of the particle.
  57943. */
  57944. this.velocity = BABYLON.Vector3.Zero();
  57945. /**
  57946. * The pivot point in the particle local space.
  57947. */
  57948. this.pivot = BABYLON.Vector3.Zero();
  57949. /**
  57950. * Must the particle be translated from its pivot point in its local space ?
  57951. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57952. * Default : false
  57953. */
  57954. this.translateFromPivot = false;
  57955. /**
  57956. * Is the particle active or not ?
  57957. */
  57958. this.alive = true;
  57959. /**
  57960. * Is the particle visible or not ?
  57961. */
  57962. this.isVisible = true;
  57963. /**
  57964. * Index of this particle in the global "positions" array (Internal use)
  57965. */
  57966. this._pos = 0;
  57967. /**
  57968. * Index of this particle in the global "indices" array (Internal use)
  57969. */
  57970. this._ind = 0;
  57971. /**
  57972. * ModelShape id of this particle
  57973. */
  57974. this.shapeId = 0;
  57975. /**
  57976. * Index of the particle in its shape id (Internal use)
  57977. */
  57978. this.idxInShape = 0;
  57979. /**
  57980. * Still set as invisible in order to skip useless computations (Internal use)
  57981. */
  57982. this._stillInvisible = false;
  57983. /**
  57984. * Last computed particle rotation matrix
  57985. */
  57986. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57987. /**
  57988. * Parent particle Id, if any.
  57989. * Default null.
  57990. */
  57991. this.parentId = null;
  57992. /**
  57993. * Internal global position in the SPS.
  57994. */
  57995. this._globalPosition = BABYLON.Vector3.Zero();
  57996. this.idx = particleIndex;
  57997. this._pos = positionIndex;
  57998. this._ind = indiceIndex;
  57999. this._model = model;
  58000. this.shapeId = shapeId;
  58001. this.idxInShape = idxInShape;
  58002. this._sps = sps;
  58003. if (modelBoundingInfo) {
  58004. this._modelBoundingInfo = modelBoundingInfo;
  58005. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58006. }
  58007. }
  58008. Object.defineProperty(SolidParticle.prototype, "scale", {
  58009. /**
  58010. * Legacy support, changed scale to scaling
  58011. */
  58012. get: function () {
  58013. return this.scaling;
  58014. },
  58015. /**
  58016. * Legacy support, changed scale to scaling
  58017. */
  58018. set: function (scale) {
  58019. this.scaling = scale;
  58020. },
  58021. enumerable: true,
  58022. configurable: true
  58023. });
  58024. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58025. /**
  58026. * Legacy support, changed quaternion to rotationQuaternion
  58027. */
  58028. get: function () {
  58029. return this.rotationQuaternion;
  58030. },
  58031. /**
  58032. * Legacy support, changed quaternion to rotationQuaternion
  58033. */
  58034. set: function (q) {
  58035. this.rotationQuaternion = q;
  58036. },
  58037. enumerable: true,
  58038. configurable: true
  58039. });
  58040. /**
  58041. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58042. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58043. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58044. * @returns true if it intersects
  58045. */
  58046. SolidParticle.prototype.intersectsMesh = function (target) {
  58047. if (!this._boundingInfo || !target._boundingInfo) {
  58048. return false;
  58049. }
  58050. if (this._sps._bSphereOnly) {
  58051. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58052. }
  58053. return this._boundingInfo.intersects(target._boundingInfo, false);
  58054. };
  58055. return SolidParticle;
  58056. }());
  58057. BABYLON.SolidParticle = SolidParticle;
  58058. /**
  58059. * Represents the shape of the model used by one particle of a solid particle system.
  58060. * SPS internal tool, don't use it manually.
  58061. */
  58062. var ModelShape = /** @class */ (function () {
  58063. /**
  58064. * 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.
  58065. * SPS internal tool, don't use it manually.
  58066. * @hidden
  58067. */
  58068. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58069. /**
  58070. * length of the shape in the model indices array (internal use)
  58071. */
  58072. this._indicesLength = 0;
  58073. this.shapeID = id;
  58074. this._shape = shape;
  58075. this._indicesLength = indicesLength;
  58076. this._shapeUV = shapeUV;
  58077. this._positionFunction = posFunction;
  58078. this._vertexFunction = vtxFunction;
  58079. }
  58080. return ModelShape;
  58081. }());
  58082. BABYLON.ModelShape = ModelShape;
  58083. /**
  58084. * Represents a Depth Sorted Particle in the solid particle system.
  58085. */
  58086. var DepthSortedParticle = /** @class */ (function () {
  58087. function DepthSortedParticle() {
  58088. /**
  58089. * Index of the particle in the "indices" array
  58090. */
  58091. this.ind = 0;
  58092. /**
  58093. * Length of the particle shape in the "indices" array
  58094. */
  58095. this.indicesLength = 0;
  58096. /**
  58097. * Squared distance from the particle to the camera
  58098. */
  58099. this.sqDistance = 0.0;
  58100. }
  58101. return DepthSortedParticle;
  58102. }());
  58103. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58104. })(BABYLON || (BABYLON = {}));
  58105. //# sourceMappingURL=babylon.solidParticle.js.map
  58106. var BABYLON;
  58107. (function (BABYLON) {
  58108. /**
  58109. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58110. *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.
  58111. * The SPS is also a particle system. It provides some methods to manage the particles.
  58112. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58113. *
  58114. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58115. */
  58116. var SolidParticleSystem = /** @class */ (function () {
  58117. /**
  58118. * Creates a SPS (Solid Particle System) object.
  58119. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58120. * @param scene (Scene) is the scene in which the SPS is added.
  58121. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58122. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58123. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58124. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58125. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58126. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58127. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58128. */
  58129. function SolidParticleSystem(name, scene, options) {
  58130. /**
  58131. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58132. * Example : var p = SPS.particles[i];
  58133. */
  58134. this.particles = new Array();
  58135. /**
  58136. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58137. */
  58138. this.nbParticles = 0;
  58139. /**
  58140. * If the particles must ever face the camera (default false). Useful for planar particles.
  58141. */
  58142. this.billboard = false;
  58143. /**
  58144. * Recompute normals when adding a shape
  58145. */
  58146. this.recomputeNormals = true;
  58147. /**
  58148. * This a counter ofr your own usage. It's not set by any SPS functions.
  58149. */
  58150. this.counter = 0;
  58151. /**
  58152. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58153. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58154. */
  58155. this.vars = {};
  58156. /**
  58157. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58158. */
  58159. this._bSphereOnly = false;
  58160. /**
  58161. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58162. */
  58163. this._bSphereRadiusFactor = 1.0;
  58164. this._positions = new Array();
  58165. this._indices = new Array();
  58166. this._normals = new Array();
  58167. this._colors = new Array();
  58168. this._uvs = new Array();
  58169. this._index = 0; // indices index
  58170. this._updatable = true;
  58171. this._pickable = false;
  58172. this._isVisibilityBoxLocked = false;
  58173. this._alwaysVisible = false;
  58174. this._depthSort = false;
  58175. this._shapeCounter = 0;
  58176. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58177. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58178. this._computeParticleColor = true;
  58179. this._computeParticleTexture = true;
  58180. this._computeParticleRotation = true;
  58181. this._computeParticleVertex = false;
  58182. this._computeBoundingBox = false;
  58183. this._depthSortParticles = true;
  58184. this._cam_axisZ = BABYLON.Vector3.Zero();
  58185. this._cam_axisY = BABYLON.Vector3.Zero();
  58186. this._cam_axisX = BABYLON.Vector3.Zero();
  58187. this._axisZ = BABYLON.Axis.Z;
  58188. this._camDir = BABYLON.Vector3.Zero();
  58189. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58190. this._rotMatrix = new BABYLON.Matrix();
  58191. this._invertMatrix = new BABYLON.Matrix();
  58192. this._rotated = BABYLON.Vector3.Zero();
  58193. this._quaternion = new BABYLON.Quaternion();
  58194. this._vertex = BABYLON.Vector3.Zero();
  58195. this._normal = BABYLON.Vector3.Zero();
  58196. this._yaw = 0.0;
  58197. this._pitch = 0.0;
  58198. this._roll = 0.0;
  58199. this._halfroll = 0.0;
  58200. this._halfpitch = 0.0;
  58201. this._halfyaw = 0.0;
  58202. this._sinRoll = 0.0;
  58203. this._cosRoll = 0.0;
  58204. this._sinPitch = 0.0;
  58205. this._cosPitch = 0.0;
  58206. this._sinYaw = 0.0;
  58207. this._cosYaw = 0.0;
  58208. this._mustUnrotateFixedNormals = false;
  58209. this._minimum = BABYLON.Vector3.Zero();
  58210. this._maximum = BABYLON.Vector3.Zero();
  58211. this._minBbox = BABYLON.Vector3.Zero();
  58212. this._maxBbox = BABYLON.Vector3.Zero();
  58213. this._particlesIntersect = false;
  58214. this._depthSortFunction = function (p1, p2) {
  58215. return (p2.sqDistance - p1.sqDistance);
  58216. };
  58217. this._needs32Bits = false;
  58218. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58219. this._scaledPivot = BABYLON.Vector3.Zero();
  58220. this._particleHasParent = false;
  58221. this.name = name;
  58222. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58223. this._camera = scene.activeCamera;
  58224. this._pickable = options ? options.isPickable : false;
  58225. this._depthSort = options ? options.enableDepthSort : false;
  58226. this._particlesIntersect = options ? options.particleIntersection : false;
  58227. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58228. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58229. if (options && options.updatable !== undefined) {
  58230. this._updatable = options.updatable;
  58231. }
  58232. else {
  58233. this._updatable = true;
  58234. }
  58235. if (this._pickable) {
  58236. this.pickedParticles = [];
  58237. }
  58238. if (this._depthSort) {
  58239. this.depthSortedParticles = [];
  58240. }
  58241. }
  58242. /**
  58243. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58244. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58245. * @returns the created mesh
  58246. */
  58247. SolidParticleSystem.prototype.buildMesh = function () {
  58248. if (this.nbParticles === 0) {
  58249. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58250. this.addShape(triangle, 1);
  58251. triangle.dispose();
  58252. }
  58253. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58254. this._positions32 = new Float32Array(this._positions);
  58255. this._uvs32 = new Float32Array(this._uvs);
  58256. this._colors32 = new Float32Array(this._colors);
  58257. if (this.recomputeNormals) {
  58258. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58259. }
  58260. this._normals32 = new Float32Array(this._normals);
  58261. this._fixedNormal32 = new Float32Array(this._normals);
  58262. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58263. this._unrotateFixedNormals();
  58264. }
  58265. var vertexData = new BABYLON.VertexData();
  58266. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58267. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58268. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58269. if (this._uvs32.length > 0) {
  58270. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58271. }
  58272. if (this._colors32.length > 0) {
  58273. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58274. }
  58275. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58276. vertexData.applyToMesh(mesh, this._updatable);
  58277. this.mesh = mesh;
  58278. this.mesh.isPickable = this._pickable;
  58279. // free memory
  58280. if (!this._depthSort) {
  58281. this._indices = null;
  58282. }
  58283. this._positions = null;
  58284. this._normals = null;
  58285. this._uvs = null;
  58286. this._colors = null;
  58287. if (!this._updatable) {
  58288. this.particles.length = 0;
  58289. }
  58290. return mesh;
  58291. };
  58292. /**
  58293. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58294. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58295. * Thus the particles generated from `digest()` have their property `position` set yet.
  58296. * @param mesh ( Mesh ) is the mesh to be digested
  58297. * @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
  58298. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58299. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58300. * @returns the current SPS
  58301. */
  58302. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58303. var size = (options && options.facetNb) || 1;
  58304. var number = (options && options.number) || 0;
  58305. var delta = (options && options.delta) || 0;
  58306. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58307. var meshInd = mesh.getIndices();
  58308. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58309. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58310. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58311. var f = 0; // facet counter
  58312. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58313. // compute size from number
  58314. if (number) {
  58315. number = (number > totalFacets) ? totalFacets : number;
  58316. size = Math.round(totalFacets / number);
  58317. delta = 0;
  58318. }
  58319. else {
  58320. size = (size > totalFacets) ? totalFacets : size;
  58321. }
  58322. var facetPos = []; // submesh positions
  58323. var facetInd = []; // submesh indices
  58324. var facetUV = []; // submesh UV
  58325. var facetCol = []; // submesh colors
  58326. var barycenter = BABYLON.Vector3.Zero();
  58327. var sizeO = size;
  58328. while (f < totalFacets) {
  58329. size = sizeO + Math.floor((1 + delta) * Math.random());
  58330. if (f > totalFacets - size) {
  58331. size = totalFacets - f;
  58332. }
  58333. // reset temp arrays
  58334. facetPos.length = 0;
  58335. facetInd.length = 0;
  58336. facetUV.length = 0;
  58337. facetCol.length = 0;
  58338. // iterate over "size" facets
  58339. var fi = 0;
  58340. for (var j = f * 3; j < (f + size) * 3; j++) {
  58341. facetInd.push(fi);
  58342. var i = meshInd[j];
  58343. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58344. if (meshUV) {
  58345. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58346. }
  58347. if (meshCol) {
  58348. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58349. }
  58350. fi++;
  58351. }
  58352. // create a model shape for each single particle
  58353. var idx = this.nbParticles;
  58354. var shape = this._posToShape(facetPos);
  58355. var shapeUV = this._uvsToShapeUV(facetUV);
  58356. // compute the barycenter of the shape
  58357. var v;
  58358. for (v = 0; v < shape.length; v++) {
  58359. barycenter.addInPlace(shape[v]);
  58360. }
  58361. barycenter.scaleInPlace(1 / shape.length);
  58362. // shift the shape from its barycenter to the origin
  58363. for (v = 0; v < shape.length; v++) {
  58364. shape[v].subtractInPlace(barycenter);
  58365. }
  58366. var bInfo;
  58367. if (this._particlesIntersect) {
  58368. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58369. }
  58370. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58371. // add the particle in the SPS
  58372. var currentPos = this._positions.length;
  58373. var currentInd = this._indices.length;
  58374. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58375. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58376. // initialize the particle position
  58377. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58378. this._index += shape.length;
  58379. idx++;
  58380. this.nbParticles++;
  58381. this._shapeCounter++;
  58382. f += size;
  58383. }
  58384. return this;
  58385. };
  58386. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58387. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58388. var index = 0;
  58389. var idx = 0;
  58390. for (var p = 0; p < this.particles.length; p++) {
  58391. this._particle = this.particles[p];
  58392. this._shape = this._particle._model._shape;
  58393. if (this._particle.rotationQuaternion) {
  58394. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58395. }
  58396. else {
  58397. this._yaw = this._particle.rotation.y;
  58398. this._pitch = this._particle.rotation.x;
  58399. this._roll = this._particle.rotation.z;
  58400. this._quaternionRotationYPR();
  58401. }
  58402. this._quaternionToRotationMatrix();
  58403. this._rotMatrix.invertToRef(this._invertMatrix);
  58404. for (var pt = 0; pt < this._shape.length; pt++) {
  58405. idx = index + pt * 3;
  58406. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58407. this._fixedNormal32[idx] = this._normal.x;
  58408. this._fixedNormal32[idx + 1] = this._normal.y;
  58409. this._fixedNormal32[idx + 2] = this._normal.z;
  58410. }
  58411. index = idx + 3;
  58412. }
  58413. };
  58414. //reset copy
  58415. SolidParticleSystem.prototype._resetCopy = function () {
  58416. this._copy.position.x = 0;
  58417. this._copy.position.y = 0;
  58418. this._copy.position.z = 0;
  58419. this._copy.rotation.x = 0;
  58420. this._copy.rotation.y = 0;
  58421. this._copy.rotation.z = 0;
  58422. this._copy.rotationQuaternion = null;
  58423. this._copy.scaling.x = 1.0;
  58424. this._copy.scaling.y = 1.0;
  58425. this._copy.scaling.z = 1.0;
  58426. this._copy.uvs.x = 0;
  58427. this._copy.uvs.y = 0;
  58428. this._copy.uvs.z = 1.0;
  58429. this._copy.uvs.w = 1.0;
  58430. this._copy.color = null;
  58431. this._copy.translateFromPivot = false;
  58432. };
  58433. // _meshBuilder : inserts the shape model in the global SPS mesh
  58434. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58435. var i;
  58436. var u = 0;
  58437. var c = 0;
  58438. var n = 0;
  58439. this._resetCopy();
  58440. if (options && options.positionFunction) { // call to custom positionFunction
  58441. options.positionFunction(this._copy, idx, idxInShape);
  58442. this._mustUnrotateFixedNormals = true;
  58443. }
  58444. if (this._copy.rotationQuaternion) {
  58445. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58446. }
  58447. else {
  58448. this._yaw = this._copy.rotation.y;
  58449. this._pitch = this._copy.rotation.x;
  58450. this._roll = this._copy.rotation.z;
  58451. this._quaternionRotationYPR();
  58452. }
  58453. this._quaternionToRotationMatrix();
  58454. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58455. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58456. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58457. if (this._copy.translateFromPivot) {
  58458. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58459. }
  58460. else {
  58461. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58462. }
  58463. for (i = 0; i < shape.length; i++) {
  58464. this._vertex.x = shape[i].x;
  58465. this._vertex.y = shape[i].y;
  58466. this._vertex.z = shape[i].z;
  58467. if (options && options.vertexFunction) {
  58468. options.vertexFunction(this._copy, this._vertex, i);
  58469. }
  58470. this._vertex.x *= this._copy.scaling.x;
  58471. this._vertex.y *= this._copy.scaling.y;
  58472. this._vertex.z *= this._copy.scaling.z;
  58473. this._vertex.x -= this._scaledPivot.x;
  58474. this._vertex.y -= this._scaledPivot.y;
  58475. this._vertex.z -= this._scaledPivot.z;
  58476. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58477. this._rotated.addInPlace(this._pivotBackTranslation);
  58478. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58479. if (meshUV) {
  58480. 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);
  58481. u += 2;
  58482. }
  58483. if (this._copy.color) {
  58484. this._color = this._copy.color;
  58485. }
  58486. else if (meshCol && meshCol[c] !== undefined) {
  58487. this._color.r = meshCol[c];
  58488. this._color.g = meshCol[c + 1];
  58489. this._color.b = meshCol[c + 2];
  58490. this._color.a = meshCol[c + 3];
  58491. }
  58492. else {
  58493. this._color.r = 1.0;
  58494. this._color.g = 1.0;
  58495. this._color.b = 1.0;
  58496. this._color.a = 1.0;
  58497. }
  58498. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58499. c += 4;
  58500. if (!this.recomputeNormals && meshNor) {
  58501. this._normal.x = meshNor[n];
  58502. this._normal.y = meshNor[n + 1];
  58503. this._normal.z = meshNor[n + 2];
  58504. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58505. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58506. n += 3;
  58507. }
  58508. }
  58509. for (i = 0; i < meshInd.length; i++) {
  58510. var current_ind = p + meshInd[i];
  58511. indices.push(current_ind);
  58512. if (current_ind > 65535) {
  58513. this._needs32Bits = true;
  58514. }
  58515. }
  58516. if (this._pickable) {
  58517. var nbfaces = meshInd.length / 3;
  58518. for (i = 0; i < nbfaces; i++) {
  58519. this.pickedParticles.push({ idx: idx, faceId: i });
  58520. }
  58521. }
  58522. if (this._depthSort) {
  58523. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58524. }
  58525. return this._copy;
  58526. };
  58527. // returns a shape array from positions array
  58528. SolidParticleSystem.prototype._posToShape = function (positions) {
  58529. var shape = [];
  58530. for (var i = 0; i < positions.length; i += 3) {
  58531. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58532. }
  58533. return shape;
  58534. };
  58535. // returns a shapeUV array from a Vector4 uvs
  58536. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58537. var shapeUV = [];
  58538. if (uvs) {
  58539. for (var i = 0; i < uvs.length; i++)
  58540. shapeUV.push(uvs[i]);
  58541. }
  58542. return shapeUV;
  58543. };
  58544. // adds a new particle object in the particles array
  58545. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58546. if (bInfo === void 0) { bInfo = null; }
  58547. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58548. this.particles.push(sp);
  58549. return sp;
  58550. };
  58551. /**
  58552. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58553. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58554. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58555. * @param nb (positive integer) the number of particles to be created from this model
  58556. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58557. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58558. * @returns the number of shapes in the system
  58559. */
  58560. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58561. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58562. var meshInd = mesh.getIndices();
  58563. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58564. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58565. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58566. var bbInfo;
  58567. if (this._particlesIntersect) {
  58568. bbInfo = mesh.getBoundingInfo();
  58569. }
  58570. var shape = this._posToShape(meshPos);
  58571. var shapeUV = this._uvsToShapeUV(meshUV);
  58572. var posfunc = options ? options.positionFunction : null;
  58573. var vtxfunc = options ? options.vertexFunction : null;
  58574. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58575. // particles
  58576. var sp;
  58577. var currentCopy;
  58578. var idx = this.nbParticles;
  58579. for (var i = 0; i < nb; i++) {
  58580. var currentPos = this._positions.length;
  58581. var currentInd = this._indices.length;
  58582. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58583. if (this._updatable) {
  58584. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58585. sp.position.copyFrom(currentCopy.position);
  58586. sp.rotation.copyFrom(currentCopy.rotation);
  58587. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58588. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58589. }
  58590. if (currentCopy.color && sp.color) {
  58591. sp.color.copyFrom(currentCopy.color);
  58592. }
  58593. sp.scaling.copyFrom(currentCopy.scaling);
  58594. sp.uvs.copyFrom(currentCopy.uvs);
  58595. }
  58596. this._index += shape.length;
  58597. idx++;
  58598. }
  58599. this.nbParticles += nb;
  58600. this._shapeCounter++;
  58601. return this._shapeCounter - 1;
  58602. };
  58603. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58604. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58605. this._resetCopy();
  58606. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58607. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58608. }
  58609. if (this._copy.rotationQuaternion) {
  58610. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58611. }
  58612. else {
  58613. this._yaw = this._copy.rotation.y;
  58614. this._pitch = this._copy.rotation.x;
  58615. this._roll = this._copy.rotation.z;
  58616. this._quaternionRotationYPR();
  58617. }
  58618. this._quaternionToRotationMatrix();
  58619. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58620. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58621. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58622. if (this._copy.translateFromPivot) {
  58623. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58624. }
  58625. else {
  58626. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58627. }
  58628. this._shape = particle._model._shape;
  58629. for (var pt = 0; pt < this._shape.length; pt++) {
  58630. this._vertex.x = this._shape[pt].x;
  58631. this._vertex.y = this._shape[pt].y;
  58632. this._vertex.z = this._shape[pt].z;
  58633. if (particle._model._vertexFunction) {
  58634. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58635. }
  58636. this._vertex.x *= this._copy.scaling.x;
  58637. this._vertex.y *= this._copy.scaling.y;
  58638. this._vertex.z *= this._copy.scaling.z;
  58639. this._vertex.x -= this._scaledPivot.x;
  58640. this._vertex.y -= this._scaledPivot.y;
  58641. this._vertex.z -= this._scaledPivot.z;
  58642. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58643. this._rotated.addInPlace(this._pivotBackTranslation);
  58644. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58645. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58646. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58647. }
  58648. particle.position.x = 0.0;
  58649. particle.position.y = 0.0;
  58650. particle.position.z = 0.0;
  58651. particle.rotation.x = 0.0;
  58652. particle.rotation.y = 0.0;
  58653. particle.rotation.z = 0.0;
  58654. particle.rotationQuaternion = null;
  58655. particle.scaling.x = 1.0;
  58656. particle.scaling.y = 1.0;
  58657. particle.scaling.z = 1.0;
  58658. particle.uvs.x = 0.0;
  58659. particle.uvs.y = 0.0;
  58660. particle.uvs.z = 1.0;
  58661. particle.uvs.w = 1.0;
  58662. particle.pivot.x = 0.0;
  58663. particle.pivot.y = 0.0;
  58664. particle.pivot.z = 0.0;
  58665. particle.translateFromPivot = false;
  58666. particle.parentId = null;
  58667. };
  58668. /**
  58669. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58670. * @returns the SPS.
  58671. */
  58672. SolidParticleSystem.prototype.rebuildMesh = function () {
  58673. for (var p = 0; p < this.particles.length; p++) {
  58674. this._rebuildParticle(this.particles[p]);
  58675. }
  58676. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58677. return this;
  58678. };
  58679. /**
  58680. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58681. * This method calls `updateParticle()` for each particle of the SPS.
  58682. * For an animated SPS, it is usually called within the render loop.
  58683. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58684. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58685. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58686. * @returns the SPS.
  58687. */
  58688. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58689. if (start === void 0) { start = 0; }
  58690. if (end === void 0) { end = this.nbParticles - 1; }
  58691. if (update === void 0) { update = true; }
  58692. if (!this._updatable) {
  58693. return this;
  58694. }
  58695. // custom beforeUpdate
  58696. this.beforeUpdateParticles(start, end, update);
  58697. this._cam_axisX.x = 1.0;
  58698. this._cam_axisX.y = 0.0;
  58699. this._cam_axisX.z = 0.0;
  58700. this._cam_axisY.x = 0.0;
  58701. this._cam_axisY.y = 1.0;
  58702. this._cam_axisY.z = 0.0;
  58703. this._cam_axisZ.x = 0.0;
  58704. this._cam_axisZ.y = 0.0;
  58705. this._cam_axisZ.z = 1.0;
  58706. // cases when the World Matrix is to be computed first
  58707. if (this.billboard || this._depthSort) {
  58708. this.mesh.computeWorldMatrix(true);
  58709. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58710. }
  58711. // if the particles will always face the camera
  58712. if (this.billboard) {
  58713. // compute the camera position and un-rotate it by the current mesh rotation
  58714. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58715. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58716. this._cam_axisZ.normalize();
  58717. // same for camera up vector extracted from the cam view matrix
  58718. var view = this._camera.getViewMatrix(true);
  58719. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58720. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58721. this._cam_axisY.normalize();
  58722. this._cam_axisX.normalize();
  58723. }
  58724. // if depthSort, compute the camera global position in the mesh local system
  58725. if (this._depthSort) {
  58726. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58727. }
  58728. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58729. var idx = 0; // current position index in the global array positions32
  58730. var index = 0; // position start index in the global array positions32 of the current particle
  58731. var colidx = 0; // current color index in the global array colors32
  58732. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58733. var uvidx = 0; // current uv index in the global array uvs32
  58734. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58735. var pt = 0; // current index in the particle model shape
  58736. if (this.mesh.isFacetDataEnabled) {
  58737. this._computeBoundingBox = true;
  58738. }
  58739. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58740. if (this._computeBoundingBox) {
  58741. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58742. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58743. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58744. }
  58745. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58746. if (this.mesh._boundingInfo) {
  58747. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58748. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58749. }
  58750. }
  58751. }
  58752. // particle loop
  58753. index = this.particles[start]._pos;
  58754. var vpos = (index / 3) | 0;
  58755. colorIndex = vpos * 4;
  58756. uvIndex = vpos * 2;
  58757. for (var p = start; p <= end; p++) {
  58758. this._particle = this.particles[p];
  58759. this._shape = this._particle._model._shape;
  58760. this._shapeUV = this._particle._model._shapeUV;
  58761. // call to custom user function to update the particle properties
  58762. this.updateParticle(this._particle);
  58763. // camera-particle distance for depth sorting
  58764. if (this._depthSort && this._depthSortParticles) {
  58765. var dsp = this.depthSortedParticles[p];
  58766. dsp.ind = this._particle._ind;
  58767. dsp.indicesLength = this._particle._model._indicesLength;
  58768. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58769. }
  58770. // skip the computations for inactive or already invisible particles
  58771. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58772. // increment indexes for the next particle
  58773. pt = this._shape.length;
  58774. index += pt * 3;
  58775. colorIndex += pt * 4;
  58776. uvIndex += pt * 2;
  58777. continue;
  58778. }
  58779. if (this._particle.isVisible) {
  58780. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58781. this._particleHasParent = (this._particle.parentId !== null);
  58782. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58783. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58784. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58785. // particle rotation matrix
  58786. if (this.billboard) {
  58787. this._particle.rotation.x = 0.0;
  58788. this._particle.rotation.y = 0.0;
  58789. }
  58790. if (this._computeParticleRotation || this.billboard) {
  58791. if (this._particle.rotationQuaternion) {
  58792. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58793. }
  58794. else {
  58795. this._yaw = this._particle.rotation.y;
  58796. this._pitch = this._particle.rotation.x;
  58797. this._roll = this._particle.rotation.z;
  58798. this._quaternionRotationYPR();
  58799. }
  58800. this._quaternionToRotationMatrix();
  58801. }
  58802. if (this._particleHasParent) {
  58803. this._parent = this.particles[this._particle.parentId];
  58804. 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];
  58805. 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];
  58806. 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];
  58807. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58808. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58809. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58810. if (this._computeParticleRotation || this.billboard) {
  58811. 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];
  58812. 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];
  58813. 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];
  58814. 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];
  58815. 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];
  58816. 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];
  58817. 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];
  58818. 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];
  58819. 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];
  58820. }
  58821. }
  58822. else {
  58823. this._particle._globalPosition.x = this._particle.position.x;
  58824. this._particle._globalPosition.y = this._particle.position.y;
  58825. this._particle._globalPosition.z = this._particle.position.z;
  58826. if (this._computeParticleRotation || this.billboard) {
  58827. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58828. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58829. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58830. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58831. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58832. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58833. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58834. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58835. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58836. }
  58837. }
  58838. if (this._particle.translateFromPivot) {
  58839. this._pivotBackTranslation.x = 0.0;
  58840. this._pivotBackTranslation.y = 0.0;
  58841. this._pivotBackTranslation.z = 0.0;
  58842. }
  58843. else {
  58844. this._pivotBackTranslation.x = this._scaledPivot.x;
  58845. this._pivotBackTranslation.y = this._scaledPivot.y;
  58846. this._pivotBackTranslation.z = this._scaledPivot.z;
  58847. }
  58848. // particle vertex loop
  58849. for (pt = 0; pt < this._shape.length; pt++) {
  58850. idx = index + pt * 3;
  58851. colidx = colorIndex + pt * 4;
  58852. uvidx = uvIndex + pt * 2;
  58853. this._vertex.x = this._shape[pt].x;
  58854. this._vertex.y = this._shape[pt].y;
  58855. this._vertex.z = this._shape[pt].z;
  58856. if (this._computeParticleVertex) {
  58857. this.updateParticleVertex(this._particle, this._vertex, pt);
  58858. }
  58859. // positions
  58860. this._vertex.x *= this._particle.scaling.x;
  58861. this._vertex.y *= this._particle.scaling.y;
  58862. this._vertex.z *= this._particle.scaling.z;
  58863. this._vertex.x -= this._scaledPivot.x;
  58864. this._vertex.y -= this._scaledPivot.y;
  58865. this._vertex.z -= this._scaledPivot.z;
  58866. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58867. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58868. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58869. this._rotated.x += this._pivotBackTranslation.x;
  58870. this._rotated.y += this._pivotBackTranslation.y;
  58871. this._rotated.z += this._pivotBackTranslation.z;
  58872. 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;
  58873. 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;
  58874. 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;
  58875. if (this._computeBoundingBox) {
  58876. if (this._positions32[idx] < this._minimum.x) {
  58877. this._minimum.x = this._positions32[idx];
  58878. }
  58879. if (this._positions32[idx] > this._maximum.x) {
  58880. this._maximum.x = this._positions32[idx];
  58881. }
  58882. if (this._positions32[idx + 1] < this._minimum.y) {
  58883. this._minimum.y = this._positions32[idx + 1];
  58884. }
  58885. if (this._positions32[idx + 1] > this._maximum.y) {
  58886. this._maximum.y = this._positions32[idx + 1];
  58887. }
  58888. if (this._positions32[idx + 2] < this._minimum.z) {
  58889. this._minimum.z = this._positions32[idx + 2];
  58890. }
  58891. if (this._positions32[idx + 2] > this._maximum.z) {
  58892. this._maximum.z = this._positions32[idx + 2];
  58893. }
  58894. }
  58895. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58896. if (!this._computeParticleVertex) {
  58897. this._normal.x = this._fixedNormal32[idx];
  58898. this._normal.y = this._fixedNormal32[idx + 1];
  58899. this._normal.z = this._fixedNormal32[idx + 2];
  58900. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58901. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58902. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58903. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58904. 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;
  58905. 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;
  58906. }
  58907. if (this._computeParticleColor && this._particle.color) {
  58908. this._colors32[colidx] = this._particle.color.r;
  58909. this._colors32[colidx + 1] = this._particle.color.g;
  58910. this._colors32[colidx + 2] = this._particle.color.b;
  58911. this._colors32[colidx + 3] = this._particle.color.a;
  58912. }
  58913. if (this._computeParticleTexture) {
  58914. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58915. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58916. }
  58917. }
  58918. }
  58919. // particle just set invisible : scaled to zero and positioned at the origin
  58920. else {
  58921. this._particle._stillInvisible = true; // mark the particle as invisible
  58922. for (pt = 0; pt < this._shape.length; pt++) {
  58923. idx = index + pt * 3;
  58924. colidx = colorIndex + pt * 4;
  58925. uvidx = uvIndex + pt * 2;
  58926. this._positions32[idx] = 0.0;
  58927. this._positions32[idx + 1] = 0.0;
  58928. this._positions32[idx + 2] = 0.0;
  58929. this._normals32[idx] = 0.0;
  58930. this._normals32[idx + 1] = 0.0;
  58931. this._normals32[idx + 2] = 0.0;
  58932. if (this._computeParticleColor && this._particle.color) {
  58933. this._colors32[colidx] = this._particle.color.r;
  58934. this._colors32[colidx + 1] = this._particle.color.g;
  58935. this._colors32[colidx + 2] = this._particle.color.b;
  58936. this._colors32[colidx + 3] = this._particle.color.a;
  58937. }
  58938. if (this._computeParticleTexture) {
  58939. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58940. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58941. }
  58942. }
  58943. }
  58944. // if the particle intersections must be computed : update the bbInfo
  58945. if (this._particlesIntersect) {
  58946. var bInfo = this._particle._boundingInfo;
  58947. var bBox = bInfo.boundingBox;
  58948. var bSphere = bInfo.boundingSphere;
  58949. if (!this._bSphereOnly) {
  58950. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58951. for (var b = 0; b < bBox.vectors.length; b++) {
  58952. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58953. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58954. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58955. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58956. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58957. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58958. 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;
  58959. 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;
  58960. 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;
  58961. }
  58962. bBox._update(this.mesh._worldMatrix);
  58963. }
  58964. // place and scale the particle bouding sphere in the SPS local system, then update it
  58965. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58966. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58967. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58968. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58969. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58970. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58971. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58972. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58973. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58974. 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));
  58975. bSphere._update(this.mesh._worldMatrix);
  58976. }
  58977. // increment indexes for the next particle
  58978. index = idx + 3;
  58979. colorIndex = colidx + 4;
  58980. uvIndex = uvidx + 2;
  58981. }
  58982. // if the VBO must be updated
  58983. if (update) {
  58984. if (this._computeParticleColor) {
  58985. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58986. }
  58987. if (this._computeParticleTexture) {
  58988. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58989. }
  58990. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58991. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58992. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58993. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58994. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58995. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58996. for (var i = 0; i < this._normals32.length; i++) {
  58997. this._fixedNormal32[i] = this._normals32[i];
  58998. }
  58999. }
  59000. if (!this.mesh.areNormalsFrozen) {
  59001. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59002. }
  59003. }
  59004. if (this._depthSort && this._depthSortParticles) {
  59005. this.depthSortedParticles.sort(this._depthSortFunction);
  59006. var dspl = this.depthSortedParticles.length;
  59007. var sorted = 0;
  59008. var lind = 0;
  59009. var sind = 0;
  59010. var sid = 0;
  59011. for (sorted = 0; sorted < dspl; sorted++) {
  59012. lind = this.depthSortedParticles[sorted].indicesLength;
  59013. sind = this.depthSortedParticles[sorted].ind;
  59014. for (var i = 0; i < lind; i++) {
  59015. this._indices32[sid] = this._indices[sind + i];
  59016. sid++;
  59017. }
  59018. }
  59019. this.mesh.updateIndices(this._indices32);
  59020. }
  59021. }
  59022. if (this._computeBoundingBox) {
  59023. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59024. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59025. }
  59026. this.afterUpdateParticles(start, end, update);
  59027. return this;
  59028. };
  59029. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59030. this._halfroll = this._roll * 0.5;
  59031. this._halfpitch = this._pitch * 0.5;
  59032. this._halfyaw = this._yaw * 0.5;
  59033. this._sinRoll = Math.sin(this._halfroll);
  59034. this._cosRoll = Math.cos(this._halfroll);
  59035. this._sinPitch = Math.sin(this._halfpitch);
  59036. this._cosPitch = Math.cos(this._halfpitch);
  59037. this._sinYaw = Math.sin(this._halfyaw);
  59038. this._cosYaw = Math.cos(this._halfyaw);
  59039. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59040. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59041. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59042. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59043. };
  59044. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59045. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59046. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59047. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59048. this._rotMatrix.m[3] = 0;
  59049. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59050. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59051. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59052. this._rotMatrix.m[7] = 0;
  59053. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59054. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59055. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59056. this._rotMatrix.m[11] = 0;
  59057. this._rotMatrix.m[12] = 0;
  59058. this._rotMatrix.m[13] = 0;
  59059. this._rotMatrix.m[14] = 0;
  59060. this._rotMatrix.m[15] = 1.0;
  59061. };
  59062. /**
  59063. * Disposes the SPS.
  59064. */
  59065. SolidParticleSystem.prototype.dispose = function () {
  59066. this.mesh.dispose();
  59067. this.vars = null;
  59068. // drop references to internal big arrays for the GC
  59069. this._positions = null;
  59070. this._indices = null;
  59071. this._normals = null;
  59072. this._uvs = null;
  59073. this._colors = null;
  59074. this._indices32 = null;
  59075. this._positions32 = null;
  59076. this._normals32 = null;
  59077. this._fixedNormal32 = null;
  59078. this._uvs32 = null;
  59079. this._colors32 = null;
  59080. this.pickedParticles = null;
  59081. };
  59082. /**
  59083. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59084. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59085. * @returns the SPS.
  59086. */
  59087. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59088. if (!this._isVisibilityBoxLocked) {
  59089. this.mesh.refreshBoundingInfo();
  59090. }
  59091. return this;
  59092. };
  59093. /**
  59094. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59095. * @param size the size (float) of the visibility box
  59096. * note : this doesn't lock the SPS mesh bounding box.
  59097. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59098. */
  59099. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59100. var vis = size / 2;
  59101. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59102. };
  59103. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59104. /**
  59105. * Gets whether the SPS as always visible or not
  59106. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59107. */
  59108. get: function () {
  59109. return this._alwaysVisible;
  59110. },
  59111. /**
  59112. * Sets the SPS as always visible or not
  59113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59114. */
  59115. set: function (val) {
  59116. this._alwaysVisible = val;
  59117. this.mesh.alwaysSelectAsActiveMesh = val;
  59118. },
  59119. enumerable: true,
  59120. configurable: true
  59121. });
  59122. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59123. /**
  59124. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59125. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59126. */
  59127. get: function () {
  59128. return this._isVisibilityBoxLocked;
  59129. },
  59130. /**
  59131. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59132. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59133. */
  59134. set: function (val) {
  59135. this._isVisibilityBoxLocked = val;
  59136. var boundingInfo = this.mesh.getBoundingInfo();
  59137. boundingInfo.isLocked = val;
  59138. },
  59139. enumerable: true,
  59140. configurable: true
  59141. });
  59142. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59143. /**
  59144. * Gets if `setParticles()` computes the particle rotations or not.
  59145. * Default value : true. The SPS is faster when it's set to false.
  59146. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59147. */
  59148. get: function () {
  59149. return this._computeParticleRotation;
  59150. },
  59151. /**
  59152. * Tells to `setParticles()` to compute the particle rotations or not.
  59153. * Default value : true. The SPS is faster when it's set to false.
  59154. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59155. */
  59156. set: function (val) {
  59157. this._computeParticleRotation = val;
  59158. },
  59159. enumerable: true,
  59160. configurable: true
  59161. });
  59162. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59163. /**
  59164. * Gets if `setParticles()` computes the particle colors or not.
  59165. * Default value : true. The SPS is faster when it's set to false.
  59166. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59167. */
  59168. get: function () {
  59169. return this._computeParticleColor;
  59170. },
  59171. /**
  59172. * Tells to `setParticles()` to compute the particle colors or not.
  59173. * Default value : true. The SPS is faster when it's set to false.
  59174. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59175. */
  59176. set: function (val) {
  59177. this._computeParticleColor = val;
  59178. },
  59179. enumerable: true,
  59180. configurable: true
  59181. });
  59182. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59183. /**
  59184. * Gets if `setParticles()` computes the particle textures or not.
  59185. * Default value : true. The SPS is faster when it's set to false.
  59186. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59187. */
  59188. get: function () {
  59189. return this._computeParticleTexture;
  59190. },
  59191. set: function (val) {
  59192. this._computeParticleTexture = val;
  59193. },
  59194. enumerable: true,
  59195. configurable: true
  59196. });
  59197. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59198. /**
  59199. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59200. * Default value : false. The SPS is faster when it's set to false.
  59201. * Note : the particle custom vertex positions aren't stored values.
  59202. */
  59203. get: function () {
  59204. return this._computeParticleVertex;
  59205. },
  59206. /**
  59207. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59208. * Default value : false. The SPS is faster when it's set to false.
  59209. * Note : the particle custom vertex positions aren't stored values.
  59210. */
  59211. set: function (val) {
  59212. this._computeParticleVertex = val;
  59213. },
  59214. enumerable: true,
  59215. configurable: true
  59216. });
  59217. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59218. /**
  59219. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59220. */
  59221. get: function () {
  59222. return this._computeBoundingBox;
  59223. },
  59224. /**
  59225. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59226. */
  59227. set: function (val) {
  59228. this._computeBoundingBox = val;
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59234. /**
  59235. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59236. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59237. * Default : `true`
  59238. */
  59239. get: function () {
  59240. return this._depthSortParticles;
  59241. },
  59242. /**
  59243. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59244. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59245. * Default : `true`
  59246. */
  59247. set: function (val) {
  59248. this._depthSortParticles = val;
  59249. },
  59250. enumerable: true,
  59251. configurable: true
  59252. });
  59253. // =======================================================================
  59254. // Particle behavior logic
  59255. // these following methods may be overwritten by the user to fit his needs
  59256. /**
  59257. * This function does nothing. It may be overwritten to set all the particle first values.
  59258. * The SPS doesn't call this function, you may have to call it by your own.
  59259. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59260. */
  59261. SolidParticleSystem.prototype.initParticles = function () {
  59262. };
  59263. /**
  59264. * This function does nothing. It may be overwritten to recycle a particle.
  59265. * The SPS doesn't call this function, you may have to call it by your own.
  59266. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59267. * @param particle The particle to recycle
  59268. * @returns the recycled particle
  59269. */
  59270. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59271. return particle;
  59272. };
  59273. /**
  59274. * Updates a particle : this function should be overwritten by the user.
  59275. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59276. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59277. * @example : just set a particle position or velocity and recycle conditions
  59278. * @param particle The particle to update
  59279. * @returns the updated particle
  59280. */
  59281. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59282. return particle;
  59283. };
  59284. /**
  59285. * Updates a vertex of a particle : it can be overwritten by the user.
  59286. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59287. * @param particle the current particle
  59288. * @param vertex the current index of the current particle
  59289. * @param pt the index of the current vertex in the particle shape
  59290. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59291. * @example : just set a vertex particle position
  59292. * @returns the updated vertex
  59293. */
  59294. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59295. return vertex;
  59296. };
  59297. /**
  59298. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59299. * This does nothing and may be overwritten by the user.
  59300. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59301. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59302. * @param update the boolean update value actually passed to setParticles()
  59303. */
  59304. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59305. };
  59306. /**
  59307. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59308. * This will be passed three parameters.
  59309. * This does nothing and may be overwritten by the user.
  59310. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59311. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59312. * @param update the boolean update value actually passed to setParticles()
  59313. */
  59314. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59315. };
  59316. return SolidParticleSystem;
  59317. }());
  59318. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59319. })(BABYLON || (BABYLON = {}));
  59320. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59321. var BABYLON;
  59322. (function (BABYLON) {
  59323. var ShaderMaterial = /** @class */ (function (_super) {
  59324. __extends(ShaderMaterial, _super);
  59325. function ShaderMaterial(name, scene, shaderPath, options) {
  59326. var _this = _super.call(this, name, scene) || this;
  59327. _this._textures = {};
  59328. _this._textureArrays = {};
  59329. _this._floats = {};
  59330. _this._ints = {};
  59331. _this._floatsArrays = {};
  59332. _this._colors3 = {};
  59333. _this._colors3Arrays = {};
  59334. _this._colors4 = {};
  59335. _this._vectors2 = {};
  59336. _this._vectors3 = {};
  59337. _this._vectors4 = {};
  59338. _this._matrices = {};
  59339. _this._matrices3x3 = {};
  59340. _this._matrices2x2 = {};
  59341. _this._vectors2Arrays = {};
  59342. _this._vectors3Arrays = {};
  59343. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59344. _this._shaderPath = shaderPath;
  59345. options.needAlphaBlending = options.needAlphaBlending || false;
  59346. options.needAlphaTesting = options.needAlphaTesting || false;
  59347. options.attributes = options.attributes || ["position", "normal", "uv"];
  59348. options.uniforms = options.uniforms || ["worldViewProjection"];
  59349. options.uniformBuffers = options.uniformBuffers || [];
  59350. options.samplers = options.samplers || [];
  59351. options.defines = options.defines || [];
  59352. _this._options = options;
  59353. return _this;
  59354. }
  59355. ShaderMaterial.prototype.getClassName = function () {
  59356. return "ShaderMaterial";
  59357. };
  59358. ShaderMaterial.prototype.needAlphaBlending = function () {
  59359. return this._options.needAlphaBlending;
  59360. };
  59361. ShaderMaterial.prototype.needAlphaTesting = function () {
  59362. return this._options.needAlphaTesting;
  59363. };
  59364. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59365. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59366. this._options.uniforms.push(uniformName);
  59367. }
  59368. };
  59369. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59370. if (this._options.samplers.indexOf(name) === -1) {
  59371. this._options.samplers.push(name);
  59372. }
  59373. this._textures[name] = texture;
  59374. return this;
  59375. };
  59376. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59377. if (this._options.samplers.indexOf(name) === -1) {
  59378. this._options.samplers.push(name);
  59379. }
  59380. this._checkUniform(name);
  59381. this._textureArrays[name] = textures;
  59382. return this;
  59383. };
  59384. ShaderMaterial.prototype.setFloat = function (name, value) {
  59385. this._checkUniform(name);
  59386. this._floats[name] = value;
  59387. return this;
  59388. };
  59389. ShaderMaterial.prototype.setInt = function (name, value) {
  59390. this._checkUniform(name);
  59391. this._ints[name] = value;
  59392. return this;
  59393. };
  59394. ShaderMaterial.prototype.setFloats = function (name, value) {
  59395. this._checkUniform(name);
  59396. this._floatsArrays[name] = value;
  59397. return this;
  59398. };
  59399. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59400. this._checkUniform(name);
  59401. this._colors3[name] = value;
  59402. return this;
  59403. };
  59404. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59405. this._checkUniform(name);
  59406. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59407. color.toArray(arr, arr.length);
  59408. return arr;
  59409. }, []);
  59410. return this;
  59411. };
  59412. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59413. this._checkUniform(name);
  59414. this._colors4[name] = value;
  59415. return this;
  59416. };
  59417. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59418. this._checkUniform(name);
  59419. this._vectors2[name] = value;
  59420. return this;
  59421. };
  59422. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59423. this._checkUniform(name);
  59424. this._vectors3[name] = value;
  59425. return this;
  59426. };
  59427. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59428. this._checkUniform(name);
  59429. this._vectors4[name] = value;
  59430. return this;
  59431. };
  59432. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59433. this._checkUniform(name);
  59434. this._matrices[name] = value;
  59435. return this;
  59436. };
  59437. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59438. this._checkUniform(name);
  59439. this._matrices3x3[name] = value;
  59440. return this;
  59441. };
  59442. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59443. this._checkUniform(name);
  59444. this._matrices2x2[name] = value;
  59445. return this;
  59446. };
  59447. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59448. this._checkUniform(name);
  59449. this._vectors2Arrays[name] = value;
  59450. return this;
  59451. };
  59452. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59453. this._checkUniform(name);
  59454. this._vectors3Arrays[name] = value;
  59455. return this;
  59456. };
  59457. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59458. if (!mesh) {
  59459. return true;
  59460. }
  59461. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59462. return false;
  59463. }
  59464. return false;
  59465. };
  59466. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59467. var scene = this.getScene();
  59468. var engine = scene.getEngine();
  59469. if (!this.checkReadyOnEveryCall) {
  59470. if (this._renderId === scene.getRenderId()) {
  59471. if (this._checkCache(scene, mesh, useInstances)) {
  59472. return true;
  59473. }
  59474. }
  59475. }
  59476. // Instances
  59477. var defines = [];
  59478. var attribs = [];
  59479. var fallbacks = new BABYLON.EffectFallbacks();
  59480. if (useInstances) {
  59481. defines.push("#define INSTANCES");
  59482. }
  59483. for (var index = 0; index < this._options.defines.length; index++) {
  59484. defines.push(this._options.defines[index]);
  59485. }
  59486. for (var index = 0; index < this._options.attributes.length; index++) {
  59487. attribs.push(this._options.attributes[index]);
  59488. }
  59489. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59490. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59491. defines.push("#define VERTEXCOLOR");
  59492. }
  59493. // Bones
  59494. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59497. if (mesh.numBoneInfluencers > 4) {
  59498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59500. }
  59501. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59502. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59503. fallbacks.addCPUSkinningFallback(0, mesh);
  59504. if (this._options.uniforms.indexOf("mBones") === -1) {
  59505. this._options.uniforms.push("mBones");
  59506. }
  59507. }
  59508. else {
  59509. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59510. }
  59511. // Textures
  59512. for (var name in this._textures) {
  59513. if (!this._textures[name].isReady()) {
  59514. return false;
  59515. }
  59516. }
  59517. // Alpha test
  59518. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59519. defines.push("#define ALPHATEST");
  59520. }
  59521. var previousEffect = this._effect;
  59522. var join = defines.join("\n");
  59523. this._effect = engine.createEffect(this._shaderPath, {
  59524. attributes: attribs,
  59525. uniformsNames: this._options.uniforms,
  59526. uniformBuffersNames: this._options.uniformBuffers,
  59527. samplers: this._options.samplers,
  59528. defines: join,
  59529. fallbacks: fallbacks,
  59530. onCompiled: this.onCompiled,
  59531. onError: this.onError
  59532. }, engine);
  59533. if (!this._effect.isReady()) {
  59534. return false;
  59535. }
  59536. if (previousEffect !== this._effect) {
  59537. scene.resetCachedMaterial();
  59538. }
  59539. this._renderId = scene.getRenderId();
  59540. return true;
  59541. };
  59542. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59543. var scene = this.getScene();
  59544. if (!this._effect) {
  59545. return;
  59546. }
  59547. if (this._options.uniforms.indexOf("world") !== -1) {
  59548. this._effect.setMatrix("world", world);
  59549. }
  59550. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59551. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59552. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59553. }
  59554. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59555. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59556. }
  59557. };
  59558. ShaderMaterial.prototype.bind = function (world, mesh) {
  59559. // Std values
  59560. this.bindOnlyWorldMatrix(world);
  59561. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59562. if (this._options.uniforms.indexOf("view") !== -1) {
  59563. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59564. }
  59565. if (this._options.uniforms.indexOf("projection") !== -1) {
  59566. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59567. }
  59568. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59569. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59570. }
  59571. // Bones
  59572. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59573. var name;
  59574. // Texture
  59575. for (name in this._textures) {
  59576. this._effect.setTexture(name, this._textures[name]);
  59577. }
  59578. // Texture arrays
  59579. for (name in this._textureArrays) {
  59580. this._effect.setTextureArray(name, this._textureArrays[name]);
  59581. }
  59582. // Int
  59583. for (name in this._ints) {
  59584. this._effect.setInt(name, this._ints[name]);
  59585. }
  59586. // Float
  59587. for (name in this._floats) {
  59588. this._effect.setFloat(name, this._floats[name]);
  59589. }
  59590. // Floats
  59591. for (name in this._floatsArrays) {
  59592. this._effect.setArray(name, this._floatsArrays[name]);
  59593. }
  59594. // Color3
  59595. for (name in this._colors3) {
  59596. this._effect.setColor3(name, this._colors3[name]);
  59597. }
  59598. for (name in this._colors3Arrays) {
  59599. this._effect.setArray3(name, this._colors3Arrays[name]);
  59600. }
  59601. // Color4
  59602. for (name in this._colors4) {
  59603. var color = this._colors4[name];
  59604. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59605. }
  59606. // Vector2
  59607. for (name in this._vectors2) {
  59608. this._effect.setVector2(name, this._vectors2[name]);
  59609. }
  59610. // Vector3
  59611. for (name in this._vectors3) {
  59612. this._effect.setVector3(name, this._vectors3[name]);
  59613. }
  59614. // Vector4
  59615. for (name in this._vectors4) {
  59616. this._effect.setVector4(name, this._vectors4[name]);
  59617. }
  59618. // Matrix
  59619. for (name in this._matrices) {
  59620. this._effect.setMatrix(name, this._matrices[name]);
  59621. }
  59622. // Matrix 3x3
  59623. for (name in this._matrices3x3) {
  59624. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59625. }
  59626. // Matrix 2x2
  59627. for (name in this._matrices2x2) {
  59628. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59629. }
  59630. // Vector2Array
  59631. for (name in this._vectors2Arrays) {
  59632. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59633. }
  59634. // Vector3Array
  59635. for (name in this._vectors3Arrays) {
  59636. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59637. }
  59638. }
  59639. this._afterBind(mesh);
  59640. };
  59641. ShaderMaterial.prototype.getActiveTextures = function () {
  59642. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59643. for (var name in this._textures) {
  59644. activeTextures.push(this._textures[name]);
  59645. }
  59646. for (var name in this._textureArrays) {
  59647. var array = this._textureArrays[name];
  59648. for (var index = 0; index < array.length; index++) {
  59649. activeTextures.push(array[index]);
  59650. }
  59651. }
  59652. return activeTextures;
  59653. };
  59654. ShaderMaterial.prototype.hasTexture = function (texture) {
  59655. if (_super.prototype.hasTexture.call(this, texture)) {
  59656. return true;
  59657. }
  59658. for (var name in this._textures) {
  59659. if (this._textures[name] === texture) {
  59660. return true;
  59661. }
  59662. }
  59663. for (var name in this._textureArrays) {
  59664. var array = this._textureArrays[name];
  59665. for (var index = 0; index < array.length; index++) {
  59666. if (array[index] === texture) {
  59667. return true;
  59668. }
  59669. }
  59670. }
  59671. return false;
  59672. };
  59673. ShaderMaterial.prototype.clone = function (name) {
  59674. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59675. return newShaderMaterial;
  59676. };
  59677. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59678. if (forceDisposeTextures) {
  59679. var name;
  59680. for (name in this._textures) {
  59681. this._textures[name].dispose();
  59682. }
  59683. for (name in this._textureArrays) {
  59684. var array = this._textureArrays[name];
  59685. for (var index = 0; index < array.length; index++) {
  59686. array[index].dispose();
  59687. }
  59688. }
  59689. }
  59690. this._textures = {};
  59691. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59692. };
  59693. ShaderMaterial.prototype.serialize = function () {
  59694. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59695. serializationObject.customType = "BABYLON.ShaderMaterial";
  59696. serializationObject.options = this._options;
  59697. serializationObject.shaderPath = this._shaderPath;
  59698. var name;
  59699. // Texture
  59700. serializationObject.textures = {};
  59701. for (name in this._textures) {
  59702. serializationObject.textures[name] = this._textures[name].serialize();
  59703. }
  59704. // Texture arrays
  59705. serializationObject.textureArrays = {};
  59706. for (name in this._textureArrays) {
  59707. serializationObject.textureArrays[name] = [];
  59708. var array = this._textureArrays[name];
  59709. for (var index = 0; index < array.length; index++) {
  59710. serializationObject.textureArrays[name].push(array[index].serialize());
  59711. }
  59712. }
  59713. // Float
  59714. serializationObject.floats = {};
  59715. for (name in this._floats) {
  59716. serializationObject.floats[name] = this._floats[name];
  59717. }
  59718. // Float s
  59719. serializationObject.FloatArrays = {};
  59720. for (name in this._floatsArrays) {
  59721. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59722. }
  59723. // Color3
  59724. serializationObject.colors3 = {};
  59725. for (name in this._colors3) {
  59726. serializationObject.colors3[name] = this._colors3[name].asArray();
  59727. }
  59728. // Color3 array
  59729. serializationObject.colors3Arrays = {};
  59730. for (name in this._colors3Arrays) {
  59731. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59732. }
  59733. // Color4
  59734. serializationObject.colors4 = {};
  59735. for (name in this._colors4) {
  59736. serializationObject.colors4[name] = this._colors4[name].asArray();
  59737. }
  59738. // Vector2
  59739. serializationObject.vectors2 = {};
  59740. for (name in this._vectors2) {
  59741. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59742. }
  59743. // Vector3
  59744. serializationObject.vectors3 = {};
  59745. for (name in this._vectors3) {
  59746. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59747. }
  59748. // Vector4
  59749. serializationObject.vectors4 = {};
  59750. for (name in this._vectors4) {
  59751. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59752. }
  59753. // Matrix
  59754. serializationObject.matrices = {};
  59755. for (name in this._matrices) {
  59756. serializationObject.matrices[name] = this._matrices[name].asArray();
  59757. }
  59758. // Matrix 3x3
  59759. serializationObject.matrices3x3 = {};
  59760. for (name in this._matrices3x3) {
  59761. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59762. }
  59763. // Matrix 2x2
  59764. serializationObject.matrices2x2 = {};
  59765. for (name in this._matrices2x2) {
  59766. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59767. }
  59768. // Vector2Array
  59769. serializationObject.vectors2Arrays = {};
  59770. for (name in this._vectors2Arrays) {
  59771. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59772. }
  59773. // Vector3Array
  59774. serializationObject.vectors3Arrays = {};
  59775. for (name in this._vectors3Arrays) {
  59776. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59777. }
  59778. return serializationObject;
  59779. };
  59780. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59781. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59782. var name;
  59783. // Texture
  59784. for (name in source.textures) {
  59785. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59786. }
  59787. // Texture arrays
  59788. for (name in source.textureArrays) {
  59789. var array = source.textureArrays[name];
  59790. var textureArray = new Array();
  59791. for (var index = 0; index < array.length; index++) {
  59792. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59793. }
  59794. material.setTextureArray(name, textureArray);
  59795. }
  59796. // Float
  59797. for (name in source.floats) {
  59798. material.setFloat(name, source.floats[name]);
  59799. }
  59800. // Float s
  59801. for (name in source.floatsArrays) {
  59802. material.setFloats(name, source.floatsArrays[name]);
  59803. }
  59804. // Color3
  59805. for (name in source.colors3) {
  59806. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59807. }
  59808. // Color3 arrays
  59809. for (name in source.colors3Arrays) {
  59810. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59811. if (i % 3 === 0) {
  59812. arr.push([num]);
  59813. }
  59814. else {
  59815. arr[arr.length - 1].push(num);
  59816. }
  59817. return arr;
  59818. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59819. material.setColor3Array(name, colors);
  59820. }
  59821. // Color4
  59822. for (name in source.colors4) {
  59823. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59824. }
  59825. // Vector2
  59826. for (name in source.vectors2) {
  59827. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59828. }
  59829. // Vector3
  59830. for (name in source.vectors3) {
  59831. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59832. }
  59833. // Vector4
  59834. for (name in source.vectors4) {
  59835. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59836. }
  59837. // Matrix
  59838. for (name in source.matrices) {
  59839. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59840. }
  59841. // Matrix 3x3
  59842. for (name in source.matrices3x3) {
  59843. material.setMatrix3x3(name, source.matrices3x3[name]);
  59844. }
  59845. // Matrix 2x2
  59846. for (name in source.matrices2x2) {
  59847. material.setMatrix2x2(name, source.matrices2x2[name]);
  59848. }
  59849. // Vector2Array
  59850. for (name in source.vectors2Arrays) {
  59851. material.setArray2(name, source.vectors2Arrays[name]);
  59852. }
  59853. // Vector3Array
  59854. for (name in source.vectors3Arrays) {
  59855. material.setArray3(name, source.vectors3Arrays[name]);
  59856. }
  59857. return material;
  59858. };
  59859. return ShaderMaterial;
  59860. }(BABYLON.Material));
  59861. BABYLON.ShaderMaterial = ShaderMaterial;
  59862. })(BABYLON || (BABYLON = {}));
  59863. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59864. var BABYLON;
  59865. (function (BABYLON) {
  59866. var GroundMesh = /** @class */ (function (_super) {
  59867. __extends(GroundMesh, _super);
  59868. function GroundMesh(name, scene) {
  59869. var _this = _super.call(this, name, scene) || this;
  59870. _this.generateOctree = false;
  59871. return _this;
  59872. }
  59873. GroundMesh.prototype.getClassName = function () {
  59874. return "GroundMesh";
  59875. };
  59876. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59877. get: function () {
  59878. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59879. },
  59880. enumerable: true,
  59881. configurable: true
  59882. });
  59883. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59884. get: function () {
  59885. return this._subdivisionsX;
  59886. },
  59887. enumerable: true,
  59888. configurable: true
  59889. });
  59890. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59891. get: function () {
  59892. return this._subdivisionsY;
  59893. },
  59894. enumerable: true,
  59895. configurable: true
  59896. });
  59897. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59898. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59899. this._subdivisionsX = chunksCount;
  59900. this._subdivisionsY = chunksCount;
  59901. this.subdivide(chunksCount);
  59902. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59903. };
  59904. /**
  59905. * Returns a height (y) value in the Worl system :
  59906. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59907. * Returns the ground y position if (x, z) are outside the ground surface.
  59908. */
  59909. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59910. var world = this.getWorldMatrix();
  59911. var invMat = BABYLON.Tmp.Matrix[5];
  59912. world.invertToRef(invMat);
  59913. var tmpVect = BABYLON.Tmp.Vector3[8];
  59914. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59915. x = tmpVect.x;
  59916. z = tmpVect.z;
  59917. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59918. return this.position.y;
  59919. }
  59920. if (!this._heightQuads || this._heightQuads.length == 0) {
  59921. this._initHeightQuads();
  59922. this._computeHeightQuads();
  59923. }
  59924. var facet = this._getFacetAt(x, z);
  59925. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59926. // return y in the World system
  59927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59928. return tmpVect.y;
  59929. };
  59930. /**
  59931. * Returns a normalized vector (Vector3) orthogonal to the ground
  59932. * at the ground coordinates (x, z) expressed in the World system.
  59933. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59934. */
  59935. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59936. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59937. this.getNormalAtCoordinatesToRef(x, z, normal);
  59938. return normal;
  59939. };
  59940. /**
  59941. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59942. * at the ground coordinates (x, z) expressed in the World system.
  59943. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59944. * Returns the GroundMesh.
  59945. */
  59946. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59947. var world = this.getWorldMatrix();
  59948. var tmpMat = BABYLON.Tmp.Matrix[5];
  59949. world.invertToRef(tmpMat);
  59950. var tmpVect = BABYLON.Tmp.Vector3[8];
  59951. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59952. x = tmpVect.x;
  59953. z = tmpVect.z;
  59954. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59955. return this;
  59956. }
  59957. if (!this._heightQuads || this._heightQuads.length == 0) {
  59958. this._initHeightQuads();
  59959. this._computeHeightQuads();
  59960. }
  59961. var facet = this._getFacetAt(x, z);
  59962. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59963. return this;
  59964. };
  59965. /**
  59966. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59967. * if the ground has been updated.
  59968. * This can be used in the render loop.
  59969. * Returns the GroundMesh.
  59970. */
  59971. GroundMesh.prototype.updateCoordinateHeights = function () {
  59972. if (!this._heightQuads || this._heightQuads.length == 0) {
  59973. this._initHeightQuads();
  59974. }
  59975. this._computeHeightQuads();
  59976. return this;
  59977. };
  59978. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59979. GroundMesh.prototype._getFacetAt = function (x, z) {
  59980. // retrieve col and row from x, z coordinates in the ground local system
  59981. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59982. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59983. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59984. var facet;
  59985. if (z < quad.slope.x * x + quad.slope.y) {
  59986. facet = quad.facet1;
  59987. }
  59988. else {
  59989. facet = quad.facet2;
  59990. }
  59991. return facet;
  59992. };
  59993. // Creates and populates the heightMap array with "facet" elements :
  59994. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59995. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59996. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59997. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59998. // Returns the GroundMesh.
  59999. GroundMesh.prototype._initHeightQuads = function () {
  60000. var subdivisionsX = this._subdivisionsX;
  60001. var subdivisionsY = this._subdivisionsY;
  60002. this._heightQuads = new Array();
  60003. for (var row = 0; row < subdivisionsY; row++) {
  60004. for (var col = 0; col < subdivisionsX; col++) {
  60005. 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) };
  60006. this._heightQuads[row * subdivisionsX + col] = quad;
  60007. }
  60008. }
  60009. return this;
  60010. };
  60011. // Compute each quad element values and update the the heightMap array :
  60012. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60013. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60014. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60015. // Returns the GroundMesh.
  60016. GroundMesh.prototype._computeHeightQuads = function () {
  60017. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60018. if (!positions) {
  60019. return this;
  60020. }
  60021. var v1 = BABYLON.Tmp.Vector3[3];
  60022. var v2 = BABYLON.Tmp.Vector3[2];
  60023. var v3 = BABYLON.Tmp.Vector3[1];
  60024. var v4 = BABYLON.Tmp.Vector3[0];
  60025. var v1v2 = BABYLON.Tmp.Vector3[4];
  60026. var v1v3 = BABYLON.Tmp.Vector3[5];
  60027. var v1v4 = BABYLON.Tmp.Vector3[6];
  60028. var norm1 = BABYLON.Tmp.Vector3[7];
  60029. var norm2 = BABYLON.Tmp.Vector3[8];
  60030. var i = 0;
  60031. var j = 0;
  60032. var k = 0;
  60033. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60034. var h = 0;
  60035. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60036. var d2 = 0;
  60037. var subdivisionsX = this._subdivisionsX;
  60038. var subdivisionsY = this._subdivisionsY;
  60039. for (var row = 0; row < subdivisionsY; row++) {
  60040. for (var col = 0; col < subdivisionsX; col++) {
  60041. i = col * 3;
  60042. j = row * (subdivisionsX + 1) * 3;
  60043. k = (row + 1) * (subdivisionsX + 1) * 3;
  60044. v1.x = positions[j + i];
  60045. v1.y = positions[j + i + 1];
  60046. v1.z = positions[j + i + 2];
  60047. v2.x = positions[j + i + 3];
  60048. v2.y = positions[j + i + 4];
  60049. v2.z = positions[j + i + 5];
  60050. v3.x = positions[k + i];
  60051. v3.y = positions[k + i + 1];
  60052. v3.z = positions[k + i + 2];
  60053. v4.x = positions[k + i + 3];
  60054. v4.y = positions[k + i + 4];
  60055. v4.z = positions[k + i + 5];
  60056. // 2D slope V1V4
  60057. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60058. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60059. // facet equations :
  60060. // we compute each facet normal vector
  60061. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60062. // we compute the value d by applying the equation to v1 which belongs to the plane
  60063. // then we store the facet equation in a Vector4
  60064. v2.subtractToRef(v1, v1v2);
  60065. v3.subtractToRef(v1, v1v3);
  60066. v4.subtractToRef(v1, v1v4);
  60067. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60068. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60069. norm1.normalize();
  60070. norm2.normalize();
  60071. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60072. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60073. var quad = this._heightQuads[row * subdivisionsX + col];
  60074. quad.slope.copyFromFloats(cd, h);
  60075. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60076. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60077. }
  60078. }
  60079. return this;
  60080. };
  60081. GroundMesh.prototype.serialize = function (serializationObject) {
  60082. _super.prototype.serialize.call(this, serializationObject);
  60083. serializationObject.subdivisionsX = this._subdivisionsX;
  60084. serializationObject.subdivisionsY = this._subdivisionsY;
  60085. serializationObject.minX = this._minX;
  60086. serializationObject.maxX = this._maxX;
  60087. serializationObject.minZ = this._minZ;
  60088. serializationObject.maxZ = this._maxZ;
  60089. serializationObject.width = this._width;
  60090. serializationObject.height = this._height;
  60091. };
  60092. GroundMesh.Parse = function (parsedMesh, scene) {
  60093. var result = new GroundMesh(parsedMesh.name, scene);
  60094. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60095. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60096. result._minX = parsedMesh.minX;
  60097. result._maxX = parsedMesh.maxX;
  60098. result._minZ = parsedMesh.minZ;
  60099. result._maxZ = parsedMesh.maxZ;
  60100. result._width = parsedMesh.width;
  60101. result._height = parsedMesh.height;
  60102. return result;
  60103. };
  60104. return GroundMesh;
  60105. }(BABYLON.Mesh));
  60106. BABYLON.GroundMesh = GroundMesh;
  60107. })(BABYLON || (BABYLON = {}));
  60108. //# sourceMappingURL=babylon.groundMesh.js.map
  60109. var BABYLON;
  60110. (function (BABYLON) {
  60111. /**
  60112. * Creates an instance based on a source mesh.
  60113. */
  60114. var InstancedMesh = /** @class */ (function (_super) {
  60115. __extends(InstancedMesh, _super);
  60116. function InstancedMesh(name, source) {
  60117. var _this = _super.call(this, name, source.getScene()) || this;
  60118. source.instances.push(_this);
  60119. _this._sourceMesh = source;
  60120. _this.position.copyFrom(source.position);
  60121. _this.rotation.copyFrom(source.rotation);
  60122. _this.scaling.copyFrom(source.scaling);
  60123. if (source.rotationQuaternion) {
  60124. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60125. }
  60126. _this.infiniteDistance = source.infiniteDistance;
  60127. _this.setPivotMatrix(source.getPivotMatrix());
  60128. _this.refreshBoundingInfo();
  60129. _this._syncSubMeshes();
  60130. return _this;
  60131. }
  60132. /**
  60133. * Returns the string "InstancedMesh".
  60134. */
  60135. InstancedMesh.prototype.getClassName = function () {
  60136. return "InstancedMesh";
  60137. };
  60138. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60139. // Methods
  60140. get: function () {
  60141. return this._sourceMesh.receiveShadows;
  60142. },
  60143. enumerable: true,
  60144. configurable: true
  60145. });
  60146. Object.defineProperty(InstancedMesh.prototype, "material", {
  60147. get: function () {
  60148. return this._sourceMesh.material;
  60149. },
  60150. enumerable: true,
  60151. configurable: true
  60152. });
  60153. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60154. get: function () {
  60155. return this._sourceMesh.visibility;
  60156. },
  60157. enumerable: true,
  60158. configurable: true
  60159. });
  60160. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60161. get: function () {
  60162. return this._sourceMesh.skeleton;
  60163. },
  60164. enumerable: true,
  60165. configurable: true
  60166. });
  60167. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60168. get: function () {
  60169. return this._sourceMesh.renderingGroupId;
  60170. },
  60171. set: function (value) {
  60172. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60173. return;
  60174. }
  60175. //no-op with warning
  60176. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60177. },
  60178. enumerable: true,
  60179. configurable: true
  60180. });
  60181. /**
  60182. * Returns the total number of vertices (integer).
  60183. */
  60184. InstancedMesh.prototype.getTotalVertices = function () {
  60185. return this._sourceMesh.getTotalVertices();
  60186. };
  60187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60188. get: function () {
  60189. return this._sourceMesh;
  60190. },
  60191. enumerable: true,
  60192. configurable: true
  60193. });
  60194. /**
  60195. * Is this node ready to be used/rendered
  60196. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60197. * @return {boolean} is it ready
  60198. */
  60199. InstancedMesh.prototype.isReady = function (completeCheck) {
  60200. if (completeCheck === void 0) { completeCheck = false; }
  60201. return this._sourceMesh.isReady(completeCheck, true);
  60202. };
  60203. /**
  60204. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60205. */
  60206. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60207. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60208. };
  60209. /**
  60210. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60211. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60212. * The `data` are either a numeric array either a Float32Array.
  60213. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60214. * 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).
  60215. * Note that a new underlying VertexBuffer object is created each call.
  60216. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60217. *
  60218. * Possible `kind` values :
  60219. * - BABYLON.VertexBuffer.PositionKind
  60220. * - BABYLON.VertexBuffer.UVKind
  60221. * - BABYLON.VertexBuffer.UV2Kind
  60222. * - BABYLON.VertexBuffer.UV3Kind
  60223. * - BABYLON.VertexBuffer.UV4Kind
  60224. * - BABYLON.VertexBuffer.UV5Kind
  60225. * - BABYLON.VertexBuffer.UV6Kind
  60226. * - BABYLON.VertexBuffer.ColorKind
  60227. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60228. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60229. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60230. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60231. *
  60232. * Returns the Mesh.
  60233. */
  60234. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60235. if (this.sourceMesh) {
  60236. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60237. }
  60238. return this.sourceMesh;
  60239. };
  60240. /**
  60241. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60242. * If the mesh has no geometry, it is simply returned as it is.
  60243. * The `data` are either a numeric array either a Float32Array.
  60244. * No new underlying VertexBuffer object is created.
  60245. * 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.
  60246. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60247. *
  60248. * Possible `kind` values :
  60249. * - BABYLON.VertexBuffer.PositionKind
  60250. * - BABYLON.VertexBuffer.UVKind
  60251. * - BABYLON.VertexBuffer.UV2Kind
  60252. * - BABYLON.VertexBuffer.UV3Kind
  60253. * - BABYLON.VertexBuffer.UV4Kind
  60254. * - BABYLON.VertexBuffer.UV5Kind
  60255. * - BABYLON.VertexBuffer.UV6Kind
  60256. * - BABYLON.VertexBuffer.ColorKind
  60257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60261. *
  60262. * Returns the Mesh.
  60263. */
  60264. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60265. if (this.sourceMesh) {
  60266. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60267. }
  60268. return this.sourceMesh;
  60269. };
  60270. /**
  60271. * Sets the mesh indices.
  60272. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60273. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60274. * This method creates a new index buffer each call.
  60275. * Returns the Mesh.
  60276. */
  60277. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60278. if (totalVertices === void 0) { totalVertices = null; }
  60279. if (this.sourceMesh) {
  60280. this.sourceMesh.setIndices(indices, totalVertices);
  60281. }
  60282. return this.sourceMesh;
  60283. };
  60284. /**
  60285. * Boolean : True if the mesh owns the requested kind of data.
  60286. */
  60287. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60288. return this._sourceMesh.isVerticesDataPresent(kind);
  60289. };
  60290. /**
  60291. * Returns an array of indices (IndicesArray).
  60292. */
  60293. InstancedMesh.prototype.getIndices = function () {
  60294. return this._sourceMesh.getIndices();
  60295. };
  60296. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60297. get: function () {
  60298. return this._sourceMesh._positions;
  60299. },
  60300. enumerable: true,
  60301. configurable: true
  60302. });
  60303. /**
  60304. * Sets a new updated BoundingInfo to the mesh.
  60305. * Returns the mesh.
  60306. */
  60307. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60308. var meshBB = this._sourceMesh.getBoundingInfo();
  60309. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60310. this._updateBoundingInfo();
  60311. return this;
  60312. };
  60313. InstancedMesh.prototype._preActivate = function () {
  60314. if (this._currentLOD) {
  60315. this._currentLOD._preActivate();
  60316. }
  60317. return this;
  60318. };
  60319. InstancedMesh.prototype._activate = function (renderId) {
  60320. if (this._currentLOD) {
  60321. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60322. }
  60323. return this;
  60324. };
  60325. /**
  60326. * Returns the current associated LOD AbstractMesh.
  60327. */
  60328. InstancedMesh.prototype.getLOD = function (camera) {
  60329. if (!camera) {
  60330. return this;
  60331. }
  60332. var boundingInfo = this.getBoundingInfo();
  60333. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60334. if (this._currentLOD === this.sourceMesh) {
  60335. return this;
  60336. }
  60337. return this._currentLOD;
  60338. };
  60339. InstancedMesh.prototype._syncSubMeshes = function () {
  60340. this.releaseSubMeshes();
  60341. if (this._sourceMesh.subMeshes) {
  60342. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60343. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60344. }
  60345. }
  60346. return this;
  60347. };
  60348. InstancedMesh.prototype._generatePointsArray = function () {
  60349. return this._sourceMesh._generatePointsArray();
  60350. };
  60351. /**
  60352. * Creates a new InstancedMesh from the current mesh.
  60353. * - name (string) : the cloned mesh name
  60354. * - newParent (optional Node) : the optional Node to parent the clone to.
  60355. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60356. *
  60357. * Returns the clone.
  60358. */
  60359. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60360. var result = this._sourceMesh.createInstance(name);
  60361. // Deep copy
  60362. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60363. // Bounding info
  60364. this.refreshBoundingInfo();
  60365. // Parent
  60366. if (newParent) {
  60367. result.parent = newParent;
  60368. }
  60369. if (!doNotCloneChildren) {
  60370. // Children
  60371. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60372. var mesh = this.getScene().meshes[index];
  60373. if (mesh.parent === this) {
  60374. mesh.clone(mesh.name, result);
  60375. }
  60376. }
  60377. }
  60378. result.computeWorldMatrix(true);
  60379. return result;
  60380. };
  60381. /**
  60382. * Disposes the InstancedMesh.
  60383. * Returns nothing.
  60384. */
  60385. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60386. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60387. // Remove from mesh
  60388. var index = this._sourceMesh.instances.indexOf(this);
  60389. this._sourceMesh.instances.splice(index, 1);
  60390. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60391. };
  60392. return InstancedMesh;
  60393. }(BABYLON.AbstractMesh));
  60394. BABYLON.InstancedMesh = InstancedMesh;
  60395. })(BABYLON || (BABYLON = {}));
  60396. //# sourceMappingURL=babylon.instancedMesh.js.map
  60397. var BABYLON;
  60398. (function (BABYLON) {
  60399. var LinesMesh = /** @class */ (function (_super) {
  60400. __extends(LinesMesh, _super);
  60401. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60402. if (scene === void 0) { scene = null; }
  60403. if (parent === void 0) { parent = null; }
  60404. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60405. _this.useVertexColor = useVertexColor;
  60406. _this.useVertexAlpha = useVertexAlpha;
  60407. _this.color = new BABYLON.Color3(1, 1, 1);
  60408. _this.alpha = 1;
  60409. if (source) {
  60410. _this.color = source.color.clone();
  60411. _this.alpha = source.alpha;
  60412. _this.useVertexColor = source.useVertexColor;
  60413. _this.useVertexAlpha = source.useVertexAlpha;
  60414. }
  60415. _this._intersectionThreshold = 0.1;
  60416. var defines = [];
  60417. var options = {
  60418. attributes: [BABYLON.VertexBuffer.PositionKind],
  60419. uniforms: ["world", "viewProjection"],
  60420. needAlphaBlending: true,
  60421. defines: defines
  60422. };
  60423. if (useVertexAlpha === false) {
  60424. options.needAlphaBlending = false;
  60425. }
  60426. if (!useVertexColor) {
  60427. options.uniforms.push("color");
  60428. }
  60429. else {
  60430. options.defines.push("#define VERTEXCOLOR");
  60431. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60432. }
  60433. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60434. return _this;
  60435. }
  60436. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60437. /**
  60438. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60439. * This margin is expressed in world space coordinates, so its value may vary.
  60440. * Default value is 0.1
  60441. * @returns the intersection Threshold value.
  60442. */
  60443. get: function () {
  60444. return this._intersectionThreshold;
  60445. },
  60446. /**
  60447. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60448. * This margin is expressed in world space coordinates, so its value may vary.
  60449. * @param value the new threshold to apply
  60450. */
  60451. set: function (value) {
  60452. if (this._intersectionThreshold === value) {
  60453. return;
  60454. }
  60455. this._intersectionThreshold = value;
  60456. if (this.geometry) {
  60457. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60458. }
  60459. },
  60460. enumerable: true,
  60461. configurable: true
  60462. });
  60463. /**
  60464. * Returns the string "LineMesh"
  60465. */
  60466. LinesMesh.prototype.getClassName = function () {
  60467. return "LinesMesh";
  60468. };
  60469. Object.defineProperty(LinesMesh.prototype, "material", {
  60470. get: function () {
  60471. return this._colorShader;
  60472. },
  60473. set: function (value) {
  60474. // Do nothing
  60475. },
  60476. enumerable: true,
  60477. configurable: true
  60478. });
  60479. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60480. get: function () {
  60481. return false;
  60482. },
  60483. enumerable: true,
  60484. configurable: true
  60485. });
  60486. LinesMesh.prototype.createInstance = function (name) {
  60487. throw new Error("LinesMeshes do not support createInstance.");
  60488. };
  60489. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60490. if (!this._geometry) {
  60491. return this;
  60492. }
  60493. // VBOs
  60494. this._geometry._bind(this._colorShader.getEffect());
  60495. // Color
  60496. if (!this.useVertexColor) {
  60497. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60498. }
  60499. return this;
  60500. };
  60501. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60502. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60503. return this;
  60504. }
  60505. var engine = this.getScene().getEngine();
  60506. // Draw order
  60507. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60508. return this;
  60509. };
  60510. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60511. this._colorShader.dispose();
  60512. _super.prototype.dispose.call(this, doNotRecurse);
  60513. };
  60514. /**
  60515. * Returns a new LineMesh object cloned from the current one.
  60516. */
  60517. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60518. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60519. };
  60520. return LinesMesh;
  60521. }(BABYLON.Mesh));
  60522. BABYLON.LinesMesh = LinesMesh;
  60523. })(BABYLON || (BABYLON = {}));
  60524. //# sourceMappingURL=babylon.linesMesh.js.map
  60525. var BABYLON;
  60526. (function (BABYLON) {
  60527. /**
  60528. * Class containing static functions to help procedurally build meshes
  60529. */
  60530. var MeshBuilder = /** @class */ (function () {
  60531. function MeshBuilder() {
  60532. }
  60533. MeshBuilder.updateSideOrientation = function (orientation) {
  60534. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60535. return BABYLON.Mesh.DOUBLESIDE;
  60536. }
  60537. if (orientation === undefined || orientation === null) {
  60538. return BABYLON.Mesh.FRONTSIDE;
  60539. }
  60540. return orientation;
  60541. };
  60542. /**
  60543. * Creates a box mesh
  60544. * * The parameter `size` sets the size (float) of each box side (default 1)
  60545. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60546. * * 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)
  60547. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60548. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60549. * * 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
  60550. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60551. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60552. * @param name defines the name of the mesh
  60553. * @param options defines the options used to create the mesh
  60554. * @param scene defines the hosting scene
  60555. * @returns the box mesh
  60556. */
  60557. MeshBuilder.CreateBox = function (name, options, scene) {
  60558. if (scene === void 0) { scene = null; }
  60559. var box = new BABYLON.Mesh(name, scene);
  60560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60561. box._originalBuilderSideOrientation = options.sideOrientation;
  60562. var vertexData = BABYLON.VertexData.CreateBox(options);
  60563. vertexData.applyToMesh(box, options.updatable);
  60564. return box;
  60565. };
  60566. /**
  60567. * Creates a sphere mesh
  60568. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60569. * * 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`)
  60570. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60571. * * 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
  60572. * * 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)
  60573. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60574. * * 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
  60575. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60576. * @param name defines the name of the mesh
  60577. * @param options defines the options used to create the mesh
  60578. * @param scene defines the hosting scene
  60579. * @returns the sphere mesh
  60580. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60581. */
  60582. MeshBuilder.CreateSphere = function (name, options, scene) {
  60583. var sphere = new BABYLON.Mesh(name, scene);
  60584. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60585. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60586. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60587. vertexData.applyToMesh(sphere, options.updatable);
  60588. return sphere;
  60589. };
  60590. /**
  60591. * Creates a plane polygonal mesh. By default, this is a disc
  60592. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60593. * * 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
  60594. * * 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
  60595. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60596. * * 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
  60597. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60598. * @param name defines the name of the mesh
  60599. * @param options defines the options used to create the mesh
  60600. * @param scene defines the hosting scene
  60601. * @returns the plane polygonal mesh
  60602. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60603. */
  60604. MeshBuilder.CreateDisc = function (name, options, scene) {
  60605. if (scene === void 0) { scene = null; }
  60606. var disc = new BABYLON.Mesh(name, scene);
  60607. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60608. disc._originalBuilderSideOrientation = options.sideOrientation;
  60609. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60610. vertexData.applyToMesh(disc, options.updatable);
  60611. return disc;
  60612. };
  60613. /**
  60614. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60615. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60616. * * 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`)
  60617. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60618. * * 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
  60619. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60620. * * 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
  60621. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60622. * @param name defines the name of the mesh
  60623. * @param options defines the options used to create the mesh
  60624. * @param scene defines the hosting scene
  60625. * @returns the icosahedron mesh
  60626. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60627. */
  60628. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60629. var sphere = new BABYLON.Mesh(name, scene);
  60630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60631. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60632. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60633. vertexData.applyToMesh(sphere, options.updatable);
  60634. return sphere;
  60635. };
  60636. ;
  60637. /**
  60638. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60639. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60640. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60641. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60642. * * 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
  60643. * * 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
  60644. * * 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
  60645. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60646. * * 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
  60647. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60648. * * 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
  60649. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60650. * * 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
  60651. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60652. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60653. * @param name defines the name of the mesh
  60654. * @param options defines the options used to create the mesh
  60655. * @param scene defines the hosting scene
  60656. * @returns the ribbon mesh
  60657. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60658. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60659. */
  60660. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60661. if (scene === void 0) { scene = null; }
  60662. var pathArray = options.pathArray;
  60663. var closeArray = options.closeArray;
  60664. var closePath = options.closePath;
  60665. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60666. var instance = options.instance;
  60667. var updatable = options.updatable;
  60668. if (instance) { // existing ribbon instance update
  60669. // positionFunction : ribbon case
  60670. // only pathArray and sideOrientation parameters are taken into account for positions update
  60671. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60672. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60673. var positionFunction = function (positions) {
  60674. var minlg = pathArray[0].length;
  60675. var i = 0;
  60676. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60677. for (var si = 1; si <= ns; si++) {
  60678. for (var p = 0; p < pathArray.length; p++) {
  60679. var path = pathArray[p];
  60680. var l = path.length;
  60681. minlg = (minlg < l) ? minlg : l;
  60682. var j = 0;
  60683. while (j < minlg) {
  60684. positions[i] = path[j].x;
  60685. positions[i + 1] = path[j].y;
  60686. positions[i + 2] = path[j].z;
  60687. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60688. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60689. }
  60690. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60691. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60692. }
  60693. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60694. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60695. }
  60696. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60697. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60698. }
  60699. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60700. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60701. }
  60702. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60703. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60704. }
  60705. j++;
  60706. i += 3;
  60707. }
  60708. if (instance._closePath) {
  60709. positions[i] = path[0].x;
  60710. positions[i + 1] = path[0].y;
  60711. positions[i + 2] = path[0].z;
  60712. i += 3;
  60713. }
  60714. }
  60715. }
  60716. };
  60717. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60718. positionFunction(positions);
  60719. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60720. instance._boundingInfo.update(instance._worldMatrix);
  60721. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60722. if (options.colors) {
  60723. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60724. for (var c = 0; c < options.colors.length; c++) {
  60725. colors[c * 4] = options.colors[c].r;
  60726. colors[c * 4 + 1] = options.colors[c].g;
  60727. colors[c * 4 + 2] = options.colors[c].b;
  60728. colors[c * 4 + 3] = options.colors[c].a;
  60729. }
  60730. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60731. }
  60732. if (options.uvs) {
  60733. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60734. for (var i = 0; i < options.uvs.length; i++) {
  60735. uvs[i * 2] = options.uvs[i].x;
  60736. uvs[i * 2 + 1] = options.uvs[i].y;
  60737. }
  60738. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60739. }
  60740. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60741. var indices = instance.getIndices();
  60742. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60743. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60744. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60745. if (instance._closePath) {
  60746. var indexFirst = 0;
  60747. var indexLast = 0;
  60748. for (var p = 0; p < pathArray.length; p++) {
  60749. indexFirst = instance._idx[p] * 3;
  60750. if (p + 1 < pathArray.length) {
  60751. indexLast = (instance._idx[p + 1] - 1) * 3;
  60752. }
  60753. else {
  60754. indexLast = normals.length - 3;
  60755. }
  60756. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60757. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60758. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60759. normals[indexLast] = normals[indexFirst];
  60760. normals[indexLast + 1] = normals[indexFirst + 1];
  60761. normals[indexLast + 2] = normals[indexFirst + 2];
  60762. }
  60763. }
  60764. if (!(instance.areNormalsFrozen)) {
  60765. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60766. }
  60767. }
  60768. return instance;
  60769. }
  60770. else { // new ribbon creation
  60771. var ribbon = new BABYLON.Mesh(name, scene);
  60772. ribbon._originalBuilderSideOrientation = sideOrientation;
  60773. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60774. if (closePath) {
  60775. ribbon._idx = vertexData._idx;
  60776. }
  60777. ribbon._closePath = closePath;
  60778. ribbon._closeArray = closeArray;
  60779. vertexData.applyToMesh(ribbon, updatable);
  60780. return ribbon;
  60781. }
  60782. };
  60783. /**
  60784. * Creates a cylinder or a cone mesh
  60785. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60786. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60787. * * 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.
  60788. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60789. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60790. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60791. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60792. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60793. * * 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).
  60794. * * 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
  60795. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60796. * * 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
  60797. * * 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.
  60798. * * If `enclose` is false, a ring surface is one element.
  60799. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60800. * * 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
  60801. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60802. * * 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
  60803. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60804. * @param name defines the name of the mesh
  60805. * @param options defines the options used to create the mesh
  60806. * @param scene defines the hosting scene
  60807. * @returns the cylinder mesh
  60808. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60809. */
  60810. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60811. var cylinder = new BABYLON.Mesh(name, scene);
  60812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60813. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60814. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60815. vertexData.applyToMesh(cylinder, options.updatable);
  60816. return cylinder;
  60817. };
  60818. /**
  60819. * Creates a torus mesh
  60820. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60821. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60822. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60823. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60824. * * 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
  60825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60826. * @param name defines the name of the mesh
  60827. * @param options defines the options used to create the mesh
  60828. * @param scene defines the hosting scene
  60829. * @returns the torus mesh
  60830. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60831. */
  60832. MeshBuilder.CreateTorus = function (name, options, scene) {
  60833. var torus = new BABYLON.Mesh(name, scene);
  60834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60835. torus._originalBuilderSideOrientation = options.sideOrientation;
  60836. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60837. vertexData.applyToMesh(torus, options.updatable);
  60838. return torus;
  60839. };
  60840. /**
  60841. * Creates a torus knot mesh
  60842. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60843. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60844. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60845. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60846. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60847. * * 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
  60848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60849. * @param name defines the name of the mesh
  60850. * @param options defines the options used to create the mesh
  60851. * @param scene defines the hosting scene
  60852. * @returns the torus knot mesh
  60853. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60854. */
  60855. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60856. var torusKnot = new BABYLON.Mesh(name, scene);
  60857. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60858. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60859. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60860. vertexData.applyToMesh(torusKnot, options.updatable);
  60861. return torusKnot;
  60862. };
  60863. /**
  60864. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60865. * * 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
  60866. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60867. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60868. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60869. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60870. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60871. * * 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
  60872. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60873. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60874. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60875. * @param name defines the name of the new line system
  60876. * @param options defines the options used to create the line system
  60877. * @param scene defines the hosting scene
  60878. * @returns a new line system mesh
  60879. */
  60880. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60881. var instance = options.instance;
  60882. var lines = options.lines;
  60883. var colors = options.colors;
  60884. if (instance) { // lines update
  60885. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60886. var vertexColor;
  60887. var lineColors;
  60888. if (colors) {
  60889. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60890. }
  60891. var i = 0;
  60892. var c = 0;
  60893. for (var l = 0; l < lines.length; l++) {
  60894. var points = lines[l];
  60895. for (var p = 0; p < points.length; p++) {
  60896. positions[i] = points[p].x;
  60897. positions[i + 1] = points[p].y;
  60898. positions[i + 2] = points[p].z;
  60899. if (colors && vertexColor) {
  60900. lineColors = colors[l];
  60901. vertexColor[c] = lineColors[p].r;
  60902. vertexColor[c + 1] = lineColors[p].g;
  60903. vertexColor[c + 2] = lineColors[p].b;
  60904. vertexColor[c + 3] = lineColors[p].a;
  60905. c += 4;
  60906. }
  60907. i += 3;
  60908. }
  60909. }
  60910. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60911. if (colors && vertexColor) {
  60912. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60913. }
  60914. return instance;
  60915. }
  60916. // line system creation
  60917. var useVertexColor = (colors) ? true : false;
  60918. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60919. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60920. vertexData.applyToMesh(lineSystem, options.updatable);
  60921. return lineSystem;
  60922. };
  60923. /**
  60924. * Creates a line mesh
  60925. * 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
  60926. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60927. * * The parameter `points` is an array successive Vector3
  60928. * * 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
  60929. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60930. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60931. * * When updating an instance, remember that only point positions can change, not the number of points
  60932. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60933. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60934. * @param name defines the name of the new line system
  60935. * @param options defines the options used to create the line system
  60936. * @param scene defines the hosting scene
  60937. * @returns a new line mesh
  60938. */
  60939. MeshBuilder.CreateLines = function (name, options, scene) {
  60940. if (scene === void 0) { scene = null; }
  60941. var colors = (options.colors) ? [options.colors] : null;
  60942. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60943. return lines;
  60944. };
  60945. /**
  60946. * Creates a dashed line mesh
  60947. * * 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
  60948. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60949. * * The parameter `points` is an array successive Vector3
  60950. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60951. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60952. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60953. * * 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
  60954. * * When updating an instance, remember that only point positions can change, not the number of points
  60955. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60956. * @param name defines the name of the mesh
  60957. * @param options defines the options used to create the mesh
  60958. * @param scene defines the hosting scene
  60959. * @returns the dashed line mesh
  60960. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60961. */
  60962. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60963. if (scene === void 0) { scene = null; }
  60964. var points = options.points;
  60965. var instance = options.instance;
  60966. var gapSize = options.gapSize || 1;
  60967. var dashSize = options.dashSize || 3;
  60968. if (instance) { // dashed lines update
  60969. var positionFunction = function (positions) {
  60970. var curvect = BABYLON.Vector3.Zero();
  60971. var nbSeg = positions.length / 6;
  60972. var lg = 0;
  60973. var nb = 0;
  60974. var shft = 0;
  60975. var dashshft = 0;
  60976. var curshft = 0;
  60977. var p = 0;
  60978. var i = 0;
  60979. var j = 0;
  60980. for (i = 0; i < points.length - 1; i++) {
  60981. points[i + 1].subtractToRef(points[i], curvect);
  60982. lg += curvect.length();
  60983. }
  60984. shft = lg / nbSeg;
  60985. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60986. for (i = 0; i < points.length - 1; i++) {
  60987. points[i + 1].subtractToRef(points[i], curvect);
  60988. nb = Math.floor(curvect.length() / shft);
  60989. curvect.normalize();
  60990. j = 0;
  60991. while (j < nb && p < positions.length) {
  60992. curshft = shft * j;
  60993. positions[p] = points[i].x + curshft * curvect.x;
  60994. positions[p + 1] = points[i].y + curshft * curvect.y;
  60995. positions[p + 2] = points[i].z + curshft * curvect.z;
  60996. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60997. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60998. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60999. p += 6;
  61000. j++;
  61001. }
  61002. }
  61003. while (p < positions.length) {
  61004. positions[p] = points[i].x;
  61005. positions[p + 1] = points[i].y;
  61006. positions[p + 2] = points[i].z;
  61007. p += 3;
  61008. }
  61009. };
  61010. instance.updateMeshPositions(positionFunction, false);
  61011. return instance;
  61012. }
  61013. // dashed lines creation
  61014. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61015. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61016. vertexData.applyToMesh(dashedLines, options.updatable);
  61017. dashedLines.dashSize = dashSize;
  61018. dashedLines.gapSize = gapSize;
  61019. return dashedLines;
  61020. };
  61021. /**
  61022. * 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.
  61023. * * 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.
  61024. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61025. * * 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.
  61026. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61027. * * 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
  61028. * * 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
  61029. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61030. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61031. * * 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
  61032. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61033. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61034. * @param name defines the name of the mesh
  61035. * @param options defines the options used to create the mesh
  61036. * @param scene defines the hosting scene
  61037. * @returns the extruded shape mesh
  61038. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61039. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61040. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61041. */
  61042. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61043. if (scene === void 0) { scene = null; }
  61044. var path = options.path;
  61045. var shape = options.shape;
  61046. var scale = options.scale || 1;
  61047. var rotation = options.rotation || 0;
  61048. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61049. var updatable = options.updatable;
  61050. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61051. var instance = options.instance || null;
  61052. var invertUV = options.invertUV || false;
  61053. 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);
  61054. };
  61055. /**
  61056. * Creates an custom extruded shape mesh.
  61057. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61058. * * 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.
  61059. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61060. * * 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
  61061. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61062. * * 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
  61063. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61064. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61065. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61066. * * 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
  61067. * * 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
  61068. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61069. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61070. * * 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
  61071. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61072. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61073. * @param name defines the name of the mesh
  61074. * @param options defines the options used to create the mesh
  61075. * @param scene defines the hosting scene
  61076. * @returns the custom extruded shape mesh
  61077. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61078. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61079. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61080. */
  61081. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61082. var path = options.path;
  61083. var shape = options.shape;
  61084. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61085. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61086. var ribbonCloseArray = options.ribbonCloseArray || false;
  61087. var ribbonClosePath = options.ribbonClosePath || false;
  61088. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61089. var updatable = options.updatable;
  61090. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61091. var instance = options.instance;
  61092. var invertUV = options.invertUV || false;
  61093. 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);
  61094. };
  61095. /**
  61096. * Creates lathe mesh.
  61097. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61098. * * 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
  61099. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61100. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61101. * * 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
  61102. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61103. * * 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
  61104. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61105. * * 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
  61106. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61107. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61108. * @param name defines the name of the mesh
  61109. * @param options defines the options used to create the mesh
  61110. * @param scene defines the hosting scene
  61111. * @returns the lathe mesh
  61112. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61113. */
  61114. MeshBuilder.CreateLathe = function (name, options, scene) {
  61115. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61116. var closed = (options.closed === undefined) ? true : options.closed;
  61117. var shape = options.shape;
  61118. var radius = options.radius || 1;
  61119. var tessellation = options.tessellation || 64;
  61120. var updatable = options.updatable;
  61121. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61122. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61123. var pi2 = Math.PI * 2;
  61124. var paths = new Array();
  61125. var invertUV = options.invertUV || false;
  61126. var i = 0;
  61127. var p = 0;
  61128. var step = pi2 / tessellation * arc;
  61129. var rotated;
  61130. var path = new Array();
  61131. for (i = 0; i <= tessellation; i++) {
  61132. var path = [];
  61133. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61134. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61135. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61136. }
  61137. for (p = 0; p < shape.length; p++) {
  61138. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61139. path.push(rotated);
  61140. }
  61141. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61142. 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));
  61143. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61144. }
  61145. paths.push(path);
  61146. }
  61147. // lathe ribbon
  61148. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61149. return lathe;
  61150. };
  61151. /**
  61152. * Creates a plane mesh
  61153. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61154. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61155. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61156. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61157. * * 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
  61158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61159. * @param name defines the name of the mesh
  61160. * @param options defines the options used to create the mesh
  61161. * @param scene defines the hosting scene
  61162. * @returns the plane mesh
  61163. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61164. */
  61165. MeshBuilder.CreatePlane = function (name, options, scene) {
  61166. var plane = new BABYLON.Mesh(name, scene);
  61167. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61168. plane._originalBuilderSideOrientation = options.sideOrientation;
  61169. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61170. vertexData.applyToMesh(plane, options.updatable);
  61171. if (options.sourcePlane) {
  61172. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61173. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61174. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61175. plane.rotate(vectorProduct, product);
  61176. }
  61177. return plane;
  61178. };
  61179. /**
  61180. * Creates a ground mesh
  61181. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61182. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61184. * @param name defines the name of the mesh
  61185. * @param options defines the options used to create the mesh
  61186. * @param scene defines the hosting scene
  61187. * @returns the ground mesh
  61188. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61189. */
  61190. MeshBuilder.CreateGround = function (name, options, scene) {
  61191. var ground = new BABYLON.GroundMesh(name, scene);
  61192. ground._setReady(false);
  61193. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61194. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61195. ground._width = options.width || 1;
  61196. ground._height = options.height || 1;
  61197. ground._maxX = ground._width / 2;
  61198. ground._maxZ = ground._height / 2;
  61199. ground._minX = -ground._maxX;
  61200. ground._minZ = -ground._maxZ;
  61201. var vertexData = BABYLON.VertexData.CreateGround(options);
  61202. vertexData.applyToMesh(ground, options.updatable);
  61203. ground._setReady(true);
  61204. return ground;
  61205. };
  61206. /**
  61207. * Creates a tiled ground mesh
  61208. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61209. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61210. * * 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
  61211. * * 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
  61212. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61213. * @param name defines the name of the mesh
  61214. * @param options defines the options used to create the mesh
  61215. * @param scene defines the hosting scene
  61216. * @returns the tiled ground mesh
  61217. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61218. */
  61219. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61220. var tiledGround = new BABYLON.Mesh(name, scene);
  61221. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61222. vertexData.applyToMesh(tiledGround, options.updatable);
  61223. return tiledGround;
  61224. };
  61225. /**
  61226. * Creates a ground mesh from a height map
  61227. * * The parameter `url` sets the URL of the height map image resource.
  61228. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61229. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61230. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61231. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61232. * * 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.
  61233. * * 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).
  61234. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61235. * @param name defines the name of the mesh
  61236. * @param url defines the url to the height map
  61237. * @param options defines the options used to create the mesh
  61238. * @param scene defines the hosting scene
  61239. * @returns the ground mesh
  61240. * @see http://doc.babylonjs.com/babylon101/height_map
  61241. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61242. */
  61243. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61244. var width = options.width || 10.0;
  61245. var height = options.height || 10.0;
  61246. var subdivisions = options.subdivisions || 1 | 0;
  61247. var minHeight = options.minHeight || 0.0;
  61248. var maxHeight = options.maxHeight || 1.0;
  61249. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61250. var updatable = options.updatable;
  61251. var onReady = options.onReady;
  61252. var ground = new BABYLON.GroundMesh(name, scene);
  61253. ground._subdivisionsX = subdivisions;
  61254. ground._subdivisionsY = subdivisions;
  61255. ground._width = width;
  61256. ground._height = height;
  61257. ground._maxX = ground._width / 2.0;
  61258. ground._maxZ = ground._height / 2.0;
  61259. ground._minX = -ground._maxX;
  61260. ground._minZ = -ground._maxZ;
  61261. ground._setReady(false);
  61262. var onload = function (img) {
  61263. // Getting height map data
  61264. var canvas = document.createElement("canvas");
  61265. var context = canvas.getContext("2d");
  61266. if (!context) {
  61267. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61268. }
  61269. if (scene.isDisposed) {
  61270. return;
  61271. }
  61272. var bufferWidth = img.width;
  61273. var bufferHeight = img.height;
  61274. canvas.width = bufferWidth;
  61275. canvas.height = bufferHeight;
  61276. context.drawImage(img, 0, 0);
  61277. // Create VertexData from map data
  61278. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61279. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61280. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61281. width: width, height: height,
  61282. subdivisions: subdivisions,
  61283. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61284. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61285. });
  61286. vertexData.applyToMesh(ground, updatable);
  61287. //execute ready callback, if set
  61288. if (onReady) {
  61289. onReady(ground);
  61290. }
  61291. ground._setReady(true);
  61292. };
  61293. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61294. return ground;
  61295. };
  61296. /**
  61297. * Creates a polygon mesh
  61298. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61299. * * 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
  61300. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61302. * * 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)
  61303. * * Remember you can only change the shape positions, not their number when updating a polygon
  61304. * @param name defines the name of the mesh
  61305. * @param options defines the options used to create the mesh
  61306. * @param scene defines the hosting scene
  61307. * @returns the polygon mesh
  61308. */
  61309. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61310. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61311. var shape = options.shape;
  61312. var holes = options.holes || [];
  61313. var depth = options.depth || 0;
  61314. var contours = [];
  61315. var hole = [];
  61316. for (var i = 0; i < shape.length; i++) {
  61317. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61318. }
  61319. var epsilon = 0.00000001;
  61320. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61321. contours.pop();
  61322. }
  61323. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61324. for (var hNb = 0; hNb < holes.length; hNb++) {
  61325. hole = [];
  61326. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61327. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61328. }
  61329. polygonTriangulation.addHole(hole);
  61330. }
  61331. var polygon = polygonTriangulation.build(options.updatable, depth);
  61332. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61333. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61334. vertexData.applyToMesh(polygon, options.updatable);
  61335. return polygon;
  61336. };
  61337. ;
  61338. /**
  61339. * Creates an extruded polygon mesh, with depth in the Y direction.
  61340. * * 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)
  61341. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61342. * @param name defines the name of the mesh
  61343. * @param options defines the options used to create the mesh
  61344. * @param scene defines the hosting scene
  61345. * @returns the polygon mesh
  61346. */
  61347. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61348. return MeshBuilder.CreatePolygon(name, options, scene);
  61349. };
  61350. ;
  61351. /**
  61352. * Creates a tube mesh.
  61353. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61354. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61355. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61356. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61357. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61358. * * 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)
  61359. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61360. * * 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
  61361. * * 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
  61362. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61363. * * 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
  61364. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61365. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61366. * @param name defines the name of the mesh
  61367. * @param options defines the options used to create the mesh
  61368. * @param scene defines the hosting scene
  61369. * @returns the tube mesh
  61370. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61371. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61372. */
  61373. MeshBuilder.CreateTube = function (name, options, scene) {
  61374. var path = options.path;
  61375. var instance = options.instance;
  61376. var radius = 1.0;
  61377. if (instance) {
  61378. radius = instance.radius;
  61379. }
  61380. if (options.radius !== undefined) {
  61381. radius = options.radius;
  61382. }
  61383. ;
  61384. var tessellation = options.tessellation || 64 | 0;
  61385. var radiusFunction = options.radiusFunction || null;
  61386. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61387. var invertUV = options.invertUV || false;
  61388. var updatable = options.updatable;
  61389. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61390. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61391. // tube geometry
  61392. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61393. var tangents = path3D.getTangents();
  61394. var normals = path3D.getNormals();
  61395. var distances = path3D.getDistances();
  61396. var pi2 = Math.PI * 2;
  61397. var step = pi2 / tessellation * arc;
  61398. var returnRadius = function () { return radius; };
  61399. var radiusFunctionFinal = radiusFunction || returnRadius;
  61400. var circlePath;
  61401. var rad;
  61402. var normal;
  61403. var rotated;
  61404. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61405. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61406. for (var i = 0; i < path.length; i++) {
  61407. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61408. circlePath = Array(); // current circle array
  61409. normal = normals[i]; // current normal
  61410. for (var t = 0; t < tessellation; t++) {
  61411. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61412. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61413. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61414. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61415. circlePath[t] = rotated;
  61416. }
  61417. circlePaths[index] = circlePath;
  61418. index++;
  61419. }
  61420. // cap
  61421. var capPath = function (nbPoints, pathIndex) {
  61422. var pointCap = Array();
  61423. for (var i = 0; i < nbPoints; i++) {
  61424. pointCap.push(path[pathIndex]);
  61425. }
  61426. return pointCap;
  61427. };
  61428. switch (cap) {
  61429. case BABYLON.Mesh.NO_CAP:
  61430. break;
  61431. case BABYLON.Mesh.CAP_START:
  61432. circlePaths[0] = capPath(tessellation, 0);
  61433. circlePaths[1] = circlePaths[2].slice(0);
  61434. break;
  61435. case BABYLON.Mesh.CAP_END:
  61436. circlePaths[index] = circlePaths[index - 1].slice(0);
  61437. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61438. break;
  61439. case BABYLON.Mesh.CAP_ALL:
  61440. circlePaths[0] = capPath(tessellation, 0);
  61441. circlePaths[1] = circlePaths[2].slice(0);
  61442. circlePaths[index] = circlePaths[index - 1].slice(0);
  61443. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61444. break;
  61445. default:
  61446. break;
  61447. }
  61448. return circlePaths;
  61449. };
  61450. var path3D;
  61451. var pathArray;
  61452. if (instance) { // tube update
  61453. var arc = options.arc || instance.arc;
  61454. path3D = (instance.path3D).update(path);
  61455. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61456. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61457. instance.path3D = path3D;
  61458. instance.pathArray = pathArray;
  61459. instance.arc = arc;
  61460. instance.radius = radius;
  61461. return instance;
  61462. }
  61463. // tube creation
  61464. path3D = new BABYLON.Path3D(path);
  61465. var newPathArray = new Array();
  61466. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61467. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61468. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61469. tube.pathArray = pathArray;
  61470. tube.path3D = path3D;
  61471. tube.tessellation = tessellation;
  61472. tube.cap = cap;
  61473. tube.arc = options.arc;
  61474. tube.radius = radius;
  61475. return tube;
  61476. };
  61477. /**
  61478. * Creates a polyhedron mesh
  61479. * * 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
  61480. * * The parameter `size` (positive float, default 1) sets the polygon size
  61481. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61482. * * 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`
  61483. * * 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
  61484. * * 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)`)
  61485. * * 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
  61486. * * 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
  61487. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61488. * * 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
  61489. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61490. * @param name defines the name of the mesh
  61491. * @param options defines the options used to create the mesh
  61492. * @param scene defines the hosting scene
  61493. * @returns the polyhedron mesh
  61494. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61495. */
  61496. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61497. var polyhedron = new BABYLON.Mesh(name, scene);
  61498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61499. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61500. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61501. vertexData.applyToMesh(polyhedron, options.updatable);
  61502. return polyhedron;
  61503. };
  61504. /**
  61505. * Creates a decal mesh.
  61506. * 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
  61507. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61508. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61509. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61510. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61511. * @param name defines the name of the mesh
  61512. * @param sourceMesh defines the mesh where the decal must be applied
  61513. * @param options defines the options used to create the mesh
  61514. * @param scene defines the hosting scene
  61515. * @returns the decal mesh
  61516. * @see http://doc.babylonjs.com/how_to/decals
  61517. */
  61518. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61519. var indices = sourceMesh.getIndices();
  61520. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61521. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61522. var position = options.position || BABYLON.Vector3.Zero();
  61523. var normal = options.normal || BABYLON.Vector3.Up();
  61524. var size = options.size || BABYLON.Vector3.One();
  61525. var angle = options.angle || 0;
  61526. // Getting correct rotation
  61527. if (!normal) {
  61528. var target = new BABYLON.Vector3(0, 0, 1);
  61529. var camera = sourceMesh.getScene().activeCamera;
  61530. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61531. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61532. }
  61533. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61534. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61535. var pitch = Math.atan2(normal.y, len);
  61536. // Matrix
  61537. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61538. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61539. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61540. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61541. var vertexData = new BABYLON.VertexData();
  61542. vertexData.indices = [];
  61543. vertexData.positions = [];
  61544. vertexData.normals = [];
  61545. vertexData.uvs = [];
  61546. var currentVertexDataIndex = 0;
  61547. var extractDecalVector3 = function (indexId) {
  61548. var result = new BABYLON.PositionNormalVertex();
  61549. if (!indices || !positions || !normals) {
  61550. return result;
  61551. }
  61552. var vertexId = indices[indexId];
  61553. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61554. // Send vector to decal local world
  61555. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61556. // Get normal
  61557. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61558. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61559. return result;
  61560. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61561. var clip = function (vertices, axis) {
  61562. if (vertices.length === 0) {
  61563. return vertices;
  61564. }
  61565. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61566. var clipVertices = function (v0, v1) {
  61567. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61568. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61569. };
  61570. var result = new Array();
  61571. for (var index = 0; index < vertices.length; index += 3) {
  61572. var v1Out;
  61573. var v2Out;
  61574. var v3Out;
  61575. var total = 0;
  61576. var nV1 = null;
  61577. var nV2 = null;
  61578. var nV3 = null;
  61579. var nV4 = null;
  61580. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61581. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61582. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61583. v1Out = d1 > 0;
  61584. v2Out = d2 > 0;
  61585. v3Out = d3 > 0;
  61586. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61587. switch (total) {
  61588. case 0:
  61589. result.push(vertices[index]);
  61590. result.push(vertices[index + 1]);
  61591. result.push(vertices[index + 2]);
  61592. break;
  61593. case 1:
  61594. if (v1Out) {
  61595. nV1 = vertices[index + 1];
  61596. nV2 = vertices[index + 2];
  61597. nV3 = clipVertices(vertices[index], nV1);
  61598. nV4 = clipVertices(vertices[index], nV2);
  61599. }
  61600. if (v2Out) {
  61601. nV1 = vertices[index];
  61602. nV2 = vertices[index + 2];
  61603. nV3 = clipVertices(vertices[index + 1], nV1);
  61604. nV4 = clipVertices(vertices[index + 1], nV2);
  61605. result.push(nV3);
  61606. result.push(nV2.clone());
  61607. result.push(nV1.clone());
  61608. result.push(nV2.clone());
  61609. result.push(nV3.clone());
  61610. result.push(nV4);
  61611. break;
  61612. }
  61613. if (v3Out) {
  61614. nV1 = vertices[index];
  61615. nV2 = vertices[index + 1];
  61616. nV3 = clipVertices(vertices[index + 2], nV1);
  61617. nV4 = clipVertices(vertices[index + 2], nV2);
  61618. }
  61619. if (nV1 && nV2 && nV3 && nV4) {
  61620. result.push(nV1.clone());
  61621. result.push(nV2.clone());
  61622. result.push(nV3);
  61623. result.push(nV4);
  61624. result.push(nV3.clone());
  61625. result.push(nV2.clone());
  61626. }
  61627. break;
  61628. case 2:
  61629. if (!v1Out) {
  61630. nV1 = vertices[index].clone();
  61631. nV2 = clipVertices(nV1, vertices[index + 1]);
  61632. nV3 = clipVertices(nV1, vertices[index + 2]);
  61633. result.push(nV1);
  61634. result.push(nV2);
  61635. result.push(nV3);
  61636. }
  61637. if (!v2Out) {
  61638. nV1 = vertices[index + 1].clone();
  61639. nV2 = clipVertices(nV1, vertices[index + 2]);
  61640. nV3 = clipVertices(nV1, vertices[index]);
  61641. result.push(nV1);
  61642. result.push(nV2);
  61643. result.push(nV3);
  61644. }
  61645. if (!v3Out) {
  61646. nV1 = vertices[index + 2].clone();
  61647. nV2 = clipVertices(nV1, vertices[index]);
  61648. nV3 = clipVertices(nV1, vertices[index + 1]);
  61649. result.push(nV1);
  61650. result.push(nV2);
  61651. result.push(nV3);
  61652. }
  61653. break;
  61654. case 3:
  61655. break;
  61656. }
  61657. }
  61658. return result;
  61659. };
  61660. for (var index = 0; index < indices.length; index += 3) {
  61661. var faceVertices = new Array();
  61662. faceVertices.push(extractDecalVector3(index));
  61663. faceVertices.push(extractDecalVector3(index + 1));
  61664. faceVertices.push(extractDecalVector3(index + 2));
  61665. // Clip
  61666. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61667. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61668. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61669. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61670. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61671. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61672. if (faceVertices.length === 0) {
  61673. continue;
  61674. }
  61675. // Add UVs and get back to world
  61676. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61677. var vertex = faceVertices[vIndex];
  61678. //TODO check for Int32Array | Uint32Array | Uint16Array
  61679. vertexData.indices.push(currentVertexDataIndex);
  61680. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61681. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61682. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61683. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61684. currentVertexDataIndex++;
  61685. }
  61686. }
  61687. // Return mesh
  61688. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61689. vertexData.applyToMesh(decal);
  61690. decal.position = position.clone();
  61691. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61692. return decal;
  61693. };
  61694. // Privates
  61695. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61696. // extrusion geometry
  61697. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61698. var tangents = path3D.getTangents();
  61699. var normals = path3D.getNormals();
  61700. var binormals = path3D.getBinormals();
  61701. var distances = path3D.getDistances();
  61702. var angle = 0;
  61703. var returnScale = function () { return scale !== null ? scale : 1; };
  61704. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61705. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61706. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61707. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61708. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61709. for (var i = 0; i < curve.length; i++) {
  61710. var shapePath = new Array();
  61711. var angleStep = rotate(i, distances[i]);
  61712. var scaleRatio = scl(i, distances[i]);
  61713. for (var p = 0; p < shape.length; p++) {
  61714. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61715. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61716. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61717. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61718. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61719. shapePath[p] = rotated;
  61720. }
  61721. shapePaths[index] = shapePath;
  61722. angle += angleStep;
  61723. index++;
  61724. }
  61725. // cap
  61726. var capPath = function (shapePath) {
  61727. var pointCap = Array();
  61728. var barycenter = BABYLON.Vector3.Zero();
  61729. var i;
  61730. for (i = 0; i < shapePath.length; i++) {
  61731. barycenter.addInPlace(shapePath[i]);
  61732. }
  61733. barycenter.scaleInPlace(1.0 / shapePath.length);
  61734. for (i = 0; i < shapePath.length; i++) {
  61735. pointCap.push(barycenter);
  61736. }
  61737. return pointCap;
  61738. };
  61739. switch (cap) {
  61740. case BABYLON.Mesh.NO_CAP:
  61741. break;
  61742. case BABYLON.Mesh.CAP_START:
  61743. shapePaths[0] = capPath(shapePaths[2]);
  61744. shapePaths[1] = shapePaths[2];
  61745. break;
  61746. case BABYLON.Mesh.CAP_END:
  61747. shapePaths[index] = shapePaths[index - 1];
  61748. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61749. break;
  61750. case BABYLON.Mesh.CAP_ALL:
  61751. shapePaths[0] = capPath(shapePaths[2]);
  61752. shapePaths[1] = shapePaths[2];
  61753. shapePaths[index] = shapePaths[index - 1];
  61754. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61755. break;
  61756. default:
  61757. break;
  61758. }
  61759. return shapePaths;
  61760. };
  61761. var path3D;
  61762. var pathArray;
  61763. if (instance) { // instance update
  61764. path3D = (instance.path3D).update(curve);
  61765. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61766. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61767. return instance;
  61768. }
  61769. // extruded shape creation
  61770. path3D = new BABYLON.Path3D(curve);
  61771. var newShapePaths = new Array();
  61772. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61773. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61774. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61775. extrudedGeneric.pathArray = pathArray;
  61776. extrudedGeneric.path3D = path3D;
  61777. extrudedGeneric.cap = cap;
  61778. return extrudedGeneric;
  61779. };
  61780. return MeshBuilder;
  61781. }());
  61782. BABYLON.MeshBuilder = MeshBuilder;
  61783. })(BABYLON || (BABYLON = {}));
  61784. //# sourceMappingURL=babylon.meshBuilder.js.map
  61785. var BABYLON;
  61786. (function (BABYLON) {
  61787. /**
  61788. * Draco compression (https://google.github.io/draco/)
  61789. *
  61790. * This class wraps the Draco module.
  61791. *
  61792. * **Encoder**
  61793. *
  61794. * The encoder is not currently implemented.
  61795. *
  61796. * **Decoder**
  61797. *
  61798. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61799. *
  61800. * To update the configuration, use the following code:
  61801. * ```javascript
  61802. * BABYLON.DracoCompression.Configuration = {
  61803. * decoder: {
  61804. * wasmUrl: "<url to the WebAssembly library>",
  61805. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61806. * fallbackUrl: "<url to the fallback JavaScript library>",
  61807. * }
  61808. * };
  61809. * ```
  61810. *
  61811. * 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.
  61812. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61813. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61814. *
  61815. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61816. * ```javascript
  61817. * var dracoCompression = new BABYLON.DracoCompression();
  61818. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61819. * [BABYLON.VertexBuffer.PositionKind]: 0
  61820. * });
  61821. * ```
  61822. *
  61823. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61824. */
  61825. var DracoCompression = /** @class */ (function () {
  61826. /**
  61827. * Constructor
  61828. */
  61829. function DracoCompression() {
  61830. }
  61831. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61832. /**
  61833. * Returns true if the decoder is available.
  61834. */
  61835. get: function () {
  61836. if (typeof DracoDecoderModule !== "undefined") {
  61837. return true;
  61838. }
  61839. var decoder = DracoCompression.Configuration.decoder;
  61840. if (decoder) {
  61841. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61842. return true;
  61843. }
  61844. if (decoder.fallbackUrl) {
  61845. return true;
  61846. }
  61847. }
  61848. return false;
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. /**
  61854. * Stop all async operations and release resources.
  61855. */
  61856. DracoCompression.prototype.dispose = function () {
  61857. };
  61858. /**
  61859. * Decode Draco compressed mesh data to vertex data.
  61860. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61861. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61862. * @returns A promise that resolves with the decoded vertex data
  61863. */
  61864. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61865. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61866. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61867. var module = wrappedModule.module;
  61868. var vertexData = new BABYLON.VertexData();
  61869. var buffer = new module.DecoderBuffer();
  61870. buffer.Init(dataView, dataView.byteLength);
  61871. var decoder = new module.Decoder();
  61872. var geometry;
  61873. var status;
  61874. try {
  61875. var type = decoder.GetEncodedGeometryType(buffer);
  61876. switch (type) {
  61877. case module.TRIANGULAR_MESH:
  61878. geometry = new module.Mesh();
  61879. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61880. break;
  61881. case module.POINT_CLOUD:
  61882. geometry = new module.PointCloud();
  61883. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61884. break;
  61885. default:
  61886. throw new Error("Invalid geometry type " + type);
  61887. }
  61888. if (!status.ok() || !geometry.ptr) {
  61889. throw new Error(status.error_msg());
  61890. }
  61891. var numPoints = geometry.num_points();
  61892. if (type === module.TRIANGULAR_MESH) {
  61893. var numFaces = geometry.num_faces();
  61894. var faceIndices = new module.DracoInt32Array();
  61895. try {
  61896. var indices = new Uint32Array(numFaces * 3);
  61897. for (var i = 0; i < numFaces; i++) {
  61898. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61899. var offset = i * 3;
  61900. indices[offset + 0] = faceIndices.GetValue(0);
  61901. indices[offset + 1] = faceIndices.GetValue(1);
  61902. indices[offset + 2] = faceIndices.GetValue(2);
  61903. }
  61904. vertexData.indices = indices;
  61905. }
  61906. finally {
  61907. module.destroy(faceIndices);
  61908. }
  61909. }
  61910. for (var kind in attributes) {
  61911. var uniqueId = attributes[kind];
  61912. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61913. var dracoData = new module.DracoFloat32Array();
  61914. try {
  61915. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61916. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61917. for (var i = 0; i < babylonData.length; i++) {
  61918. babylonData[i] = dracoData.GetValue(i);
  61919. }
  61920. vertexData.set(babylonData, kind);
  61921. }
  61922. finally {
  61923. module.destroy(dracoData);
  61924. }
  61925. }
  61926. }
  61927. finally {
  61928. if (geometry) {
  61929. module.destroy(geometry);
  61930. }
  61931. module.destroy(decoder);
  61932. module.destroy(buffer);
  61933. }
  61934. return vertexData;
  61935. });
  61936. };
  61937. DracoCompression._GetDecoderModule = function () {
  61938. if (!DracoCompression._DecoderModulePromise) {
  61939. var promise = null;
  61940. var config_1 = {};
  61941. if (typeof DracoDecoderModule !== "undefined") {
  61942. promise = Promise.resolve();
  61943. }
  61944. else {
  61945. var decoder = DracoCompression.Configuration.decoder;
  61946. if (decoder) {
  61947. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61948. promise = Promise.all([
  61949. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61950. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61951. config_1.wasmBinary = data;
  61952. })
  61953. ]);
  61954. }
  61955. else if (decoder.fallbackUrl) {
  61956. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61957. }
  61958. }
  61959. }
  61960. if (!promise) {
  61961. throw new Error("Draco decoder module is not available");
  61962. }
  61963. DracoCompression._DecoderModulePromise = promise.then(function () {
  61964. return new Promise(function (resolve) {
  61965. config_1.onModuleLoaded = function (decoderModule) {
  61966. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61967. resolve({ module: decoderModule });
  61968. };
  61969. DracoDecoderModule(config_1);
  61970. });
  61971. });
  61972. }
  61973. return DracoCompression._DecoderModulePromise;
  61974. };
  61975. DracoCompression._LoadScriptAsync = function (url) {
  61976. return new Promise(function (resolve, reject) {
  61977. BABYLON.Tools.LoadScript(url, function () {
  61978. resolve();
  61979. }, function (message) {
  61980. reject(new Error(message));
  61981. });
  61982. });
  61983. };
  61984. DracoCompression._LoadFileAsync = function (url) {
  61985. return new Promise(function (resolve, reject) {
  61986. BABYLON.Tools.LoadFile(url, function (data) {
  61987. resolve(data);
  61988. }, undefined, undefined, true, function (request, exception) {
  61989. reject(exception);
  61990. });
  61991. });
  61992. };
  61993. /**
  61994. * The configuration. Defaults to the following urls:
  61995. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61996. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61997. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61998. */
  61999. DracoCompression.Configuration = {
  62000. decoder: {
  62001. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62002. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62003. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62004. }
  62005. };
  62006. return DracoCompression;
  62007. }());
  62008. BABYLON.DracoCompression = DracoCompression;
  62009. })(BABYLON || (BABYLON = {}));
  62010. //# sourceMappingURL=babylon.dracoCompression.js.map
  62011. var BABYLON;
  62012. (function (BABYLON) {
  62013. var AudioEngine = /** @class */ (function () {
  62014. function AudioEngine() {
  62015. this._audioContext = null;
  62016. this._audioContextInitialized = false;
  62017. this.canUseWebAudio = false;
  62018. this.WarnedWebAudioUnsupported = false;
  62019. this.unlocked = false;
  62020. this.isMP3supported = false;
  62021. this.isOGGsupported = false;
  62022. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62023. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62024. this.canUseWebAudio = true;
  62025. }
  62026. var audioElem = document.createElement('audio');
  62027. try {
  62028. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62029. this.isMP3supported = true;
  62030. }
  62031. }
  62032. catch (e) {
  62033. // protect error during capability check.
  62034. }
  62035. try {
  62036. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62037. this.isOGGsupported = true;
  62038. }
  62039. }
  62040. catch (e) {
  62041. // protect error during capability check.
  62042. }
  62043. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62044. this._unlockiOSaudio();
  62045. }
  62046. else {
  62047. this.unlocked = true;
  62048. }
  62049. }
  62050. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62051. get: function () {
  62052. if (!this._audioContextInitialized) {
  62053. this._initializeAudioContext();
  62054. }
  62055. return this._audioContext;
  62056. },
  62057. enumerable: true,
  62058. configurable: true
  62059. });
  62060. AudioEngine.prototype._unlockiOSaudio = function () {
  62061. var _this = this;
  62062. var unlockaudio = function () {
  62063. if (!_this.audioContext) {
  62064. return;
  62065. }
  62066. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62067. var source = _this.audioContext.createBufferSource();
  62068. source.buffer = buffer;
  62069. source.connect(_this.audioContext.destination);
  62070. source.start(0);
  62071. setTimeout(function () {
  62072. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62073. _this.unlocked = true;
  62074. window.removeEventListener('touchend', unlockaudio, false);
  62075. if (_this.onAudioUnlocked) {
  62076. _this.onAudioUnlocked();
  62077. }
  62078. }
  62079. }, 0);
  62080. };
  62081. window.addEventListener('touchend', unlockaudio, false);
  62082. };
  62083. AudioEngine.prototype._initializeAudioContext = function () {
  62084. try {
  62085. if (this.canUseWebAudio) {
  62086. this._audioContext = new AudioContext();
  62087. // create a global volume gain node
  62088. this.masterGain = this._audioContext.createGain();
  62089. this.masterGain.gain.value = 1;
  62090. this.masterGain.connect(this._audioContext.destination);
  62091. this._audioContextInitialized = true;
  62092. }
  62093. }
  62094. catch (e) {
  62095. this.canUseWebAudio = false;
  62096. BABYLON.Tools.Error("Web Audio: " + e.message);
  62097. }
  62098. };
  62099. AudioEngine.prototype.dispose = function () {
  62100. if (this.canUseWebAudio && this._audioContextInitialized) {
  62101. if (this._connectedAnalyser && this._audioContext) {
  62102. this._connectedAnalyser.stopDebugCanvas();
  62103. this._connectedAnalyser.dispose();
  62104. this.masterGain.disconnect();
  62105. this.masterGain.connect(this._audioContext.destination);
  62106. this._connectedAnalyser = null;
  62107. }
  62108. this.masterGain.gain.value = 1;
  62109. }
  62110. this.WarnedWebAudioUnsupported = false;
  62111. };
  62112. AudioEngine.prototype.getGlobalVolume = function () {
  62113. if (this.canUseWebAudio && this._audioContextInitialized) {
  62114. return this.masterGain.gain.value;
  62115. }
  62116. else {
  62117. return -1;
  62118. }
  62119. };
  62120. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62121. if (this.canUseWebAudio && this._audioContextInitialized) {
  62122. this.masterGain.gain.value = newVolume;
  62123. }
  62124. };
  62125. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62126. if (this._connectedAnalyser) {
  62127. this._connectedAnalyser.stopDebugCanvas();
  62128. }
  62129. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62130. this._connectedAnalyser = analyser;
  62131. this.masterGain.disconnect();
  62132. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62133. }
  62134. };
  62135. return AudioEngine;
  62136. }());
  62137. BABYLON.AudioEngine = AudioEngine;
  62138. })(BABYLON || (BABYLON = {}));
  62139. //# sourceMappingURL=babylon.audioEngine.js.map
  62140. var BABYLON;
  62141. (function (BABYLON) {
  62142. var Sound = /** @class */ (function () {
  62143. /**
  62144. * Create a sound and attach it to a scene
  62145. * @param name Name of your sound
  62146. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62147. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62148. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62149. */
  62150. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62151. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62152. var _this = this;
  62153. this.autoplay = false;
  62154. this.loop = false;
  62155. this.useCustomAttenuation = false;
  62156. this.spatialSound = false;
  62157. this.refDistance = 1;
  62158. this.rolloffFactor = 1;
  62159. this.maxDistance = 100;
  62160. this.distanceModel = "linear";
  62161. this._panningModel = "equalpower";
  62162. this._playbackRate = 1;
  62163. this._streaming = false;
  62164. this._startTime = 0;
  62165. this._startOffset = 0;
  62166. this._position = BABYLON.Vector3.Zero();
  62167. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62168. this._volume = 1;
  62169. this._isReadyToPlay = false;
  62170. this.isPlaying = false;
  62171. this.isPaused = false;
  62172. this._isDirectional = false;
  62173. // Used if you'd like to create a directional sound.
  62174. // If not set, the sound will be omnidirectional
  62175. this._coneInnerAngle = 360;
  62176. this._coneOuterAngle = 360;
  62177. this._coneOuterGain = 0;
  62178. this._isOutputConnected = false;
  62179. this._urlType = "Unknown";
  62180. this.name = name;
  62181. this._scene = scene;
  62182. this._readyToPlayCallback = readyToPlayCallback;
  62183. // Default custom attenuation function is a linear attenuation
  62184. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62185. if (currentDistance < maxDistance) {
  62186. return currentVolume * (1 - currentDistance / maxDistance);
  62187. }
  62188. else {
  62189. return 0;
  62190. }
  62191. };
  62192. if (options) {
  62193. this.autoplay = options.autoplay || false;
  62194. this.loop = options.loop || false;
  62195. // if volume === 0, we need another way to check this option
  62196. if (options.volume !== undefined) {
  62197. this._volume = options.volume;
  62198. }
  62199. this.spatialSound = options.spatialSound || false;
  62200. this.maxDistance = options.maxDistance || 100;
  62201. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62202. this.rolloffFactor = options.rolloffFactor || 1;
  62203. this.refDistance = options.refDistance || 1;
  62204. this.distanceModel = options.distanceModel || "linear";
  62205. this._playbackRate = options.playbackRate || 1;
  62206. this._streaming = options.streaming || false;
  62207. }
  62208. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62209. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62210. this._soundGain.gain.value = this._volume;
  62211. this._inputAudioNode = this._soundGain;
  62212. this._ouputAudioNode = this._soundGain;
  62213. if (this.spatialSound) {
  62214. this._createSpatialParameters();
  62215. }
  62216. this._scene.mainSoundTrack.AddSound(this);
  62217. var validParameter = true;
  62218. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62219. if (urlOrArrayBuffer) {
  62220. try {
  62221. if (typeof (urlOrArrayBuffer) === "string") {
  62222. this._urlType = "String";
  62223. }
  62224. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62225. this._urlType = "ArrayBuffer";
  62226. }
  62227. else if (urlOrArrayBuffer instanceof MediaStream) {
  62228. this._urlType = "MediaStream";
  62229. }
  62230. else if (Array.isArray(urlOrArrayBuffer)) {
  62231. this._urlType = "Array";
  62232. }
  62233. var urls = [];
  62234. var codecSupportedFound = false;
  62235. switch (this._urlType) {
  62236. case "MediaStream":
  62237. this._streaming = true;
  62238. this._isReadyToPlay = true;
  62239. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62240. if (this.autoplay) {
  62241. this.play();
  62242. }
  62243. if (this._readyToPlayCallback) {
  62244. this._readyToPlayCallback();
  62245. }
  62246. break;
  62247. case "ArrayBuffer":
  62248. if (urlOrArrayBuffer.byteLength > 0) {
  62249. codecSupportedFound = true;
  62250. this._soundLoaded(urlOrArrayBuffer);
  62251. }
  62252. break;
  62253. case "String":
  62254. urls.push(urlOrArrayBuffer);
  62255. case "Array":
  62256. if (urls.length === 0)
  62257. urls = urlOrArrayBuffer;
  62258. // If we found a supported format, we load it immediately and stop the loop
  62259. for (var i = 0; i < urls.length; i++) {
  62260. var url = urls[i];
  62261. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62262. codecSupportedFound = true;
  62263. }
  62264. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62265. codecSupportedFound = true;
  62266. }
  62267. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62268. codecSupportedFound = true;
  62269. }
  62270. if (url.indexOf("blob:") !== -1) {
  62271. codecSupportedFound = true;
  62272. }
  62273. if (codecSupportedFound) {
  62274. // Loading sound using XHR2
  62275. if (!this._streaming) {
  62276. this._scene._loadFile(url, function (data) {
  62277. _this._soundLoaded(data);
  62278. }, undefined, true, true, function (exception) {
  62279. if (exception) {
  62280. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62281. }
  62282. BABYLON.Tools.Error("Sound creation aborted.");
  62283. _this._scene.mainSoundTrack.RemoveSound(_this);
  62284. });
  62285. }
  62286. // Streaming sound using HTML5 Audio tag
  62287. else {
  62288. this._htmlAudioElement = new Audio(url);
  62289. this._htmlAudioElement.controls = false;
  62290. this._htmlAudioElement.loop = this.loop;
  62291. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62292. this._htmlAudioElement.preload = "auto";
  62293. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62294. _this._isReadyToPlay = true;
  62295. if (_this.autoplay) {
  62296. _this.play();
  62297. }
  62298. if (_this._readyToPlayCallback) {
  62299. _this._readyToPlayCallback();
  62300. }
  62301. });
  62302. document.body.appendChild(this._htmlAudioElement);
  62303. }
  62304. break;
  62305. }
  62306. }
  62307. break;
  62308. default:
  62309. validParameter = false;
  62310. break;
  62311. }
  62312. if (!validParameter) {
  62313. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62314. }
  62315. else {
  62316. if (!codecSupportedFound) {
  62317. this._isReadyToPlay = true;
  62318. // Simulating a ready to play event to avoid breaking code path
  62319. if (this._readyToPlayCallback) {
  62320. window.setTimeout(function () {
  62321. if (_this._readyToPlayCallback) {
  62322. _this._readyToPlayCallback();
  62323. }
  62324. }, 1000);
  62325. }
  62326. }
  62327. }
  62328. }
  62329. catch (ex) {
  62330. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62331. this._scene.mainSoundTrack.RemoveSound(this);
  62332. }
  62333. }
  62334. }
  62335. else {
  62336. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62337. this._scene.mainSoundTrack.AddSound(this);
  62338. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62339. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62340. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62341. }
  62342. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62343. if (this._readyToPlayCallback) {
  62344. window.setTimeout(function () {
  62345. if (_this._readyToPlayCallback) {
  62346. _this._readyToPlayCallback();
  62347. }
  62348. }, 1000);
  62349. }
  62350. }
  62351. }
  62352. Sound.prototype.dispose = function () {
  62353. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62354. if (this.isPlaying) {
  62355. this.stop();
  62356. }
  62357. this._isReadyToPlay = false;
  62358. if (this.soundTrackId === -1) {
  62359. this._scene.mainSoundTrack.RemoveSound(this);
  62360. }
  62361. else {
  62362. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62363. }
  62364. if (this._soundGain) {
  62365. this._soundGain.disconnect();
  62366. this._soundGain = null;
  62367. }
  62368. if (this._soundPanner) {
  62369. this._soundPanner.disconnect();
  62370. this._soundPanner = null;
  62371. }
  62372. if (this._soundSource) {
  62373. this._soundSource.disconnect();
  62374. this._soundSource = null;
  62375. }
  62376. this._audioBuffer = null;
  62377. if (this._htmlAudioElement) {
  62378. this._htmlAudioElement.pause();
  62379. this._htmlAudioElement.src = "";
  62380. document.body.removeChild(this._htmlAudioElement);
  62381. }
  62382. if (this._streamingSource) {
  62383. this._streamingSource.disconnect();
  62384. }
  62385. if (this._connectedMesh && this._registerFunc) {
  62386. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62387. this._connectedMesh = null;
  62388. }
  62389. }
  62390. };
  62391. Sound.prototype.isReady = function () {
  62392. return this._isReadyToPlay;
  62393. };
  62394. Sound.prototype._soundLoaded = function (audioData) {
  62395. var _this = this;
  62396. if (!BABYLON.Engine.audioEngine.audioContext) {
  62397. return;
  62398. }
  62399. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62400. _this._audioBuffer = buffer;
  62401. _this._isReadyToPlay = true;
  62402. if (_this.autoplay) {
  62403. _this.play();
  62404. }
  62405. if (_this._readyToPlayCallback) {
  62406. _this._readyToPlayCallback();
  62407. }
  62408. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62409. };
  62410. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62411. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62412. this._audioBuffer = audioBuffer;
  62413. this._isReadyToPlay = true;
  62414. }
  62415. };
  62416. Sound.prototype.updateOptions = function (options) {
  62417. if (options) {
  62418. this.loop = options.loop || this.loop;
  62419. this.maxDistance = options.maxDistance || this.maxDistance;
  62420. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62421. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62422. this.refDistance = options.refDistance || this.refDistance;
  62423. this.distanceModel = options.distanceModel || this.distanceModel;
  62424. this._playbackRate = options.playbackRate || this._playbackRate;
  62425. this._updateSpatialParameters();
  62426. if (this.isPlaying) {
  62427. if (this._streaming && this._htmlAudioElement) {
  62428. this._htmlAudioElement.playbackRate = this._playbackRate;
  62429. }
  62430. else {
  62431. if (this._soundSource) {
  62432. this._soundSource.playbackRate.value = this._playbackRate;
  62433. }
  62434. }
  62435. }
  62436. }
  62437. };
  62438. Sound.prototype._createSpatialParameters = function () {
  62439. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62440. if (this._scene.headphone) {
  62441. this._panningModel = "HRTF";
  62442. }
  62443. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62444. this._updateSpatialParameters();
  62445. this._soundPanner.connect(this._ouputAudioNode);
  62446. this._inputAudioNode = this._soundPanner;
  62447. }
  62448. };
  62449. Sound.prototype._updateSpatialParameters = function () {
  62450. if (this.spatialSound && this._soundPanner) {
  62451. if (this.useCustomAttenuation) {
  62452. // Tricks to disable in a way embedded Web Audio attenuation
  62453. this._soundPanner.distanceModel = "linear";
  62454. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62455. this._soundPanner.refDistance = 1;
  62456. this._soundPanner.rolloffFactor = 1;
  62457. this._soundPanner.panningModel = this._panningModel;
  62458. }
  62459. else {
  62460. this._soundPanner.distanceModel = this.distanceModel;
  62461. this._soundPanner.maxDistance = this.maxDistance;
  62462. this._soundPanner.refDistance = this.refDistance;
  62463. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62464. this._soundPanner.panningModel = this._panningModel;
  62465. }
  62466. }
  62467. };
  62468. Sound.prototype.switchPanningModelToHRTF = function () {
  62469. this._panningModel = "HRTF";
  62470. this._switchPanningModel();
  62471. };
  62472. Sound.prototype.switchPanningModelToEqualPower = function () {
  62473. this._panningModel = "equalpower";
  62474. this._switchPanningModel();
  62475. };
  62476. Sound.prototype._switchPanningModel = function () {
  62477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62478. this._soundPanner.panningModel = this._panningModel;
  62479. }
  62480. };
  62481. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62482. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62483. if (this._isOutputConnected) {
  62484. this._ouputAudioNode.disconnect();
  62485. }
  62486. this._ouputAudioNode.connect(soundTrackAudioNode);
  62487. this._isOutputConnected = true;
  62488. }
  62489. };
  62490. /**
  62491. * Transform this sound into a directional source
  62492. * @param coneInnerAngle Size of the inner cone in degree
  62493. * @param coneOuterAngle Size of the outer cone in degree
  62494. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62495. */
  62496. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62497. if (coneOuterAngle < coneInnerAngle) {
  62498. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62499. return;
  62500. }
  62501. this._coneInnerAngle = coneInnerAngle;
  62502. this._coneOuterAngle = coneOuterAngle;
  62503. this._coneOuterGain = coneOuterGain;
  62504. this._isDirectional = true;
  62505. if (this.isPlaying && this.loop) {
  62506. this.stop();
  62507. this.play();
  62508. }
  62509. };
  62510. Sound.prototype.setPosition = function (newPosition) {
  62511. this._position = newPosition;
  62512. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62513. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62514. }
  62515. };
  62516. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62517. this._localDirection = newLocalDirection;
  62518. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62519. this._updateDirection();
  62520. }
  62521. };
  62522. Sound.prototype._updateDirection = function () {
  62523. if (!this._connectedMesh || !this._soundPanner) {
  62524. return;
  62525. }
  62526. var mat = this._connectedMesh.getWorldMatrix();
  62527. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62528. direction.normalize();
  62529. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62530. };
  62531. Sound.prototype.updateDistanceFromListener = function () {
  62532. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62533. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62534. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62535. }
  62536. };
  62537. Sound.prototype.setAttenuationFunction = function (callback) {
  62538. this._customAttenuationFunction = callback;
  62539. };
  62540. /**
  62541. * Play the sound
  62542. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62543. * @param offset (optional) Start the sound setting it at a specific time
  62544. */
  62545. Sound.prototype.play = function (time, offset) {
  62546. var _this = this;
  62547. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62548. try {
  62549. if (this._startOffset < 0) {
  62550. time = -this._startOffset;
  62551. this._startOffset = 0;
  62552. }
  62553. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62554. if (!this._soundSource || !this._streamingSource) {
  62555. if (this.spatialSound && this._soundPanner) {
  62556. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62557. if (this._isDirectional) {
  62558. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62559. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62560. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62561. if (this._connectedMesh) {
  62562. this._updateDirection();
  62563. }
  62564. else {
  62565. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62566. }
  62567. }
  62568. }
  62569. }
  62570. if (this._streaming) {
  62571. if (!this._streamingSource) {
  62572. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62573. this._htmlAudioElement.onended = function () { _this._onended(); };
  62574. this._htmlAudioElement.playbackRate = this._playbackRate;
  62575. }
  62576. this._streamingSource.disconnect();
  62577. this._streamingSource.connect(this._inputAudioNode);
  62578. if (this._htmlAudioElement) {
  62579. this._htmlAudioElement.play();
  62580. }
  62581. }
  62582. else {
  62583. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62584. this._soundSource.buffer = this._audioBuffer;
  62585. this._soundSource.connect(this._inputAudioNode);
  62586. this._soundSource.loop = this.loop;
  62587. this._soundSource.playbackRate.value = this._playbackRate;
  62588. this._soundSource.onended = function () { _this._onended(); };
  62589. if (this._soundSource.buffer) {
  62590. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62591. }
  62592. }
  62593. this._startTime = startTime;
  62594. this.isPlaying = true;
  62595. this.isPaused = false;
  62596. }
  62597. catch (ex) {
  62598. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62599. }
  62600. }
  62601. };
  62602. Sound.prototype._onended = function () {
  62603. this.isPlaying = false;
  62604. if (this.onended) {
  62605. this.onended();
  62606. }
  62607. };
  62608. /**
  62609. * Stop the sound
  62610. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62611. */
  62612. Sound.prototype.stop = function (time) {
  62613. if (this.isPlaying) {
  62614. if (this._streaming) {
  62615. if (this._htmlAudioElement) {
  62616. this._htmlAudioElement.pause();
  62617. // Test needed for Firefox or it will generate an Invalid State Error
  62618. if (this._htmlAudioElement.currentTime > 0) {
  62619. this._htmlAudioElement.currentTime = 0;
  62620. }
  62621. }
  62622. else {
  62623. this._streamingSource.disconnect();
  62624. }
  62625. }
  62626. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62627. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62628. this._soundSource.stop(stopTime);
  62629. this._soundSource.onended = function () { };
  62630. if (!this.isPaused) {
  62631. this._startOffset = 0;
  62632. }
  62633. }
  62634. this.isPlaying = false;
  62635. }
  62636. };
  62637. Sound.prototype.pause = function () {
  62638. if (this.isPlaying) {
  62639. this.isPaused = true;
  62640. if (this._streaming) {
  62641. if (this._htmlAudioElement) {
  62642. this._htmlAudioElement.pause();
  62643. }
  62644. else {
  62645. this._streamingSource.disconnect();
  62646. }
  62647. }
  62648. else if (BABYLON.Engine.audioEngine.audioContext) {
  62649. this.stop(0);
  62650. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62651. }
  62652. }
  62653. };
  62654. Sound.prototype.setVolume = function (newVolume, time) {
  62655. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62656. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62657. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62658. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62659. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62660. }
  62661. else {
  62662. this._soundGain.gain.value = newVolume;
  62663. }
  62664. }
  62665. this._volume = newVolume;
  62666. };
  62667. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62668. this._playbackRate = newPlaybackRate;
  62669. if (this.isPlaying) {
  62670. if (this._streaming && this._htmlAudioElement) {
  62671. this._htmlAudioElement.playbackRate = this._playbackRate;
  62672. }
  62673. else if (this._soundSource) {
  62674. this._soundSource.playbackRate.value = this._playbackRate;
  62675. }
  62676. }
  62677. };
  62678. Sound.prototype.getVolume = function () {
  62679. return this._volume;
  62680. };
  62681. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62682. var _this = this;
  62683. if (this._connectedMesh && this._registerFunc) {
  62684. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62685. this._registerFunc = null;
  62686. }
  62687. this._connectedMesh = meshToConnectTo;
  62688. if (!this.spatialSound) {
  62689. this.spatialSound = true;
  62690. this._createSpatialParameters();
  62691. if (this.isPlaying && this.loop) {
  62692. this.stop();
  62693. this.play();
  62694. }
  62695. }
  62696. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62697. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62698. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62699. };
  62700. Sound.prototype.detachFromMesh = function () {
  62701. if (this._connectedMesh && this._registerFunc) {
  62702. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62703. this._registerFunc = null;
  62704. this._connectedMesh = null;
  62705. }
  62706. };
  62707. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62708. if (!node.getBoundingInfo) {
  62709. return;
  62710. }
  62711. var mesh = node;
  62712. var boundingInfo = mesh.getBoundingInfo();
  62713. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62715. this._updateDirection();
  62716. }
  62717. };
  62718. Sound.prototype.clone = function () {
  62719. var _this = this;
  62720. if (!this._streaming) {
  62721. var setBufferAndRun = function () {
  62722. if (_this._isReadyToPlay) {
  62723. clonedSound._audioBuffer = _this.getAudioBuffer();
  62724. clonedSound._isReadyToPlay = true;
  62725. if (clonedSound.autoplay) {
  62726. clonedSound.play();
  62727. }
  62728. }
  62729. else {
  62730. window.setTimeout(setBufferAndRun, 300);
  62731. }
  62732. };
  62733. var currentOptions = {
  62734. autoplay: this.autoplay, loop: this.loop,
  62735. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62736. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62737. refDistance: this.refDistance, distanceModel: this.distanceModel
  62738. };
  62739. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62740. if (this.useCustomAttenuation) {
  62741. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62742. }
  62743. clonedSound.setPosition(this._position);
  62744. clonedSound.setPlaybackRate(this._playbackRate);
  62745. setBufferAndRun();
  62746. return clonedSound;
  62747. }
  62748. // Can't clone a streaming sound
  62749. else {
  62750. return null;
  62751. }
  62752. };
  62753. Sound.prototype.getAudioBuffer = function () {
  62754. return this._audioBuffer;
  62755. };
  62756. Sound.prototype.serialize = function () {
  62757. var serializationObject = {
  62758. name: this.name,
  62759. url: this.name,
  62760. autoplay: this.autoplay,
  62761. loop: this.loop,
  62762. volume: this._volume,
  62763. spatialSound: this.spatialSound,
  62764. maxDistance: this.maxDistance,
  62765. rolloffFactor: this.rolloffFactor,
  62766. refDistance: this.refDistance,
  62767. distanceModel: this.distanceModel,
  62768. playbackRate: this._playbackRate,
  62769. panningModel: this._panningModel,
  62770. soundTrackId: this.soundTrackId
  62771. };
  62772. if (this.spatialSound) {
  62773. if (this._connectedMesh)
  62774. serializationObject.connectedMeshId = this._connectedMesh.id;
  62775. serializationObject.position = this._position.asArray();
  62776. serializationObject.refDistance = this.refDistance;
  62777. serializationObject.distanceModel = this.distanceModel;
  62778. serializationObject.isDirectional = this._isDirectional;
  62779. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62780. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62781. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62782. serializationObject.coneOuterGain = this._coneOuterGain;
  62783. }
  62784. return serializationObject;
  62785. };
  62786. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62787. var soundName = parsedSound.name;
  62788. var soundUrl;
  62789. if (parsedSound.url) {
  62790. soundUrl = rootUrl + parsedSound.url;
  62791. }
  62792. else {
  62793. soundUrl = rootUrl + soundName;
  62794. }
  62795. var options = {
  62796. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62797. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62798. rolloffFactor: parsedSound.rolloffFactor,
  62799. refDistance: parsedSound.refDistance,
  62800. distanceModel: parsedSound.distanceModel,
  62801. playbackRate: parsedSound.playbackRate
  62802. };
  62803. var newSound;
  62804. if (!sourceSound) {
  62805. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62806. scene._addPendingData(newSound);
  62807. }
  62808. else {
  62809. var setBufferAndRun = function () {
  62810. if (sourceSound._isReadyToPlay) {
  62811. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62812. newSound._isReadyToPlay = true;
  62813. if (newSound.autoplay) {
  62814. newSound.play();
  62815. }
  62816. }
  62817. else {
  62818. window.setTimeout(setBufferAndRun, 300);
  62819. }
  62820. };
  62821. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62822. setBufferAndRun();
  62823. }
  62824. if (parsedSound.position) {
  62825. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62826. newSound.setPosition(soundPosition);
  62827. }
  62828. if (parsedSound.isDirectional) {
  62829. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62830. if (parsedSound.localDirectionToMesh) {
  62831. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62832. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62833. }
  62834. }
  62835. if (parsedSound.connectedMeshId) {
  62836. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62837. if (connectedMesh) {
  62838. newSound.attachToMesh(connectedMesh);
  62839. }
  62840. }
  62841. return newSound;
  62842. };
  62843. return Sound;
  62844. }());
  62845. BABYLON.Sound = Sound;
  62846. })(BABYLON || (BABYLON = {}));
  62847. //# sourceMappingURL=babylon.sound.js.map
  62848. var BABYLON;
  62849. (function (BABYLON) {
  62850. var SoundTrack = /** @class */ (function () {
  62851. function SoundTrack(scene, options) {
  62852. this.id = -1;
  62853. this._isMainTrack = false;
  62854. this._isInitialized = false;
  62855. this._scene = scene;
  62856. this.soundCollection = new Array();
  62857. this._options = options;
  62858. if (!this._isMainTrack) {
  62859. this._scene.soundTracks.push(this);
  62860. this.id = this._scene.soundTracks.length - 1;
  62861. }
  62862. }
  62863. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62864. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62865. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62866. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62867. if (this._options) {
  62868. if (this._options.volume) {
  62869. this._outputAudioNode.gain.value = this._options.volume;
  62870. }
  62871. if (this._options.mainTrack) {
  62872. this._isMainTrack = this._options.mainTrack;
  62873. }
  62874. }
  62875. this._isInitialized = true;
  62876. }
  62877. };
  62878. SoundTrack.prototype.dispose = function () {
  62879. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62880. if (this._connectedAnalyser) {
  62881. this._connectedAnalyser.stopDebugCanvas();
  62882. }
  62883. while (this.soundCollection.length) {
  62884. this.soundCollection[0].dispose();
  62885. }
  62886. if (this._outputAudioNode) {
  62887. this._outputAudioNode.disconnect();
  62888. }
  62889. this._outputAudioNode = null;
  62890. }
  62891. };
  62892. SoundTrack.prototype.AddSound = function (sound) {
  62893. if (!this._isInitialized) {
  62894. this._initializeSoundTrackAudioGraph();
  62895. }
  62896. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62897. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62898. }
  62899. if (sound.soundTrackId) {
  62900. if (sound.soundTrackId === -1) {
  62901. this._scene.mainSoundTrack.RemoveSound(sound);
  62902. }
  62903. else {
  62904. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62905. }
  62906. }
  62907. this.soundCollection.push(sound);
  62908. sound.soundTrackId = this.id;
  62909. };
  62910. SoundTrack.prototype.RemoveSound = function (sound) {
  62911. var index = this.soundCollection.indexOf(sound);
  62912. if (index !== -1) {
  62913. this.soundCollection.splice(index, 1);
  62914. }
  62915. };
  62916. SoundTrack.prototype.setVolume = function (newVolume) {
  62917. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62918. this._outputAudioNode.gain.value = newVolume;
  62919. }
  62920. };
  62921. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62922. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62923. for (var i = 0; i < this.soundCollection.length; i++) {
  62924. this.soundCollection[i].switchPanningModelToHRTF();
  62925. }
  62926. }
  62927. };
  62928. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62929. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62930. for (var i = 0; i < this.soundCollection.length; i++) {
  62931. this.soundCollection[i].switchPanningModelToEqualPower();
  62932. }
  62933. }
  62934. };
  62935. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62936. if (this._connectedAnalyser) {
  62937. this._connectedAnalyser.stopDebugCanvas();
  62938. }
  62939. this._connectedAnalyser = analyser;
  62940. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62941. this._outputAudioNode.disconnect();
  62942. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62943. }
  62944. };
  62945. return SoundTrack;
  62946. }());
  62947. BABYLON.SoundTrack = SoundTrack;
  62948. })(BABYLON || (BABYLON = {}));
  62949. //# sourceMappingURL=babylon.soundtrack.js.map
  62950. var BABYLON;
  62951. (function (BABYLON) {
  62952. /**
  62953. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62954. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62955. */
  62956. var Analyser = /** @class */ (function () {
  62957. /**
  62958. * Creates a new analyser
  62959. * @param scene defines hosting scene
  62960. */
  62961. function Analyser(scene) {
  62962. /**
  62963. * Gets or sets the smoothing
  62964. * @ignorenaming
  62965. */
  62966. this.SMOOTHING = 0.75;
  62967. /**
  62968. * Gets or sets the FFT table size
  62969. * @ignorenaming
  62970. */
  62971. this.FFT_SIZE = 512;
  62972. /**
  62973. * Gets or sets the bar graph amplitude
  62974. * @ignorenaming
  62975. */
  62976. this.BARGRAPHAMPLITUDE = 256;
  62977. /**
  62978. * Gets or sets the position of the debug canvas
  62979. * @ignorenaming
  62980. */
  62981. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62982. /**
  62983. * Gets or sets the debug canvas size
  62984. * @ignorenaming
  62985. */
  62986. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62987. this._scene = scene;
  62988. this._audioEngine = BABYLON.Engine.audioEngine;
  62989. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62990. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62991. this._webAudioAnalyser.minDecibels = -140;
  62992. this._webAudioAnalyser.maxDecibels = 0;
  62993. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62994. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62995. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62996. }
  62997. }
  62998. /**
  62999. * Get the number of data values you will have to play with for the visualization
  63000. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63001. * @returns a number
  63002. */
  63003. Analyser.prototype.getFrequencyBinCount = function () {
  63004. if (this._audioEngine.canUseWebAudio) {
  63005. return this._webAudioAnalyser.frequencyBinCount;
  63006. }
  63007. else {
  63008. return 0;
  63009. }
  63010. };
  63011. /**
  63012. * Gets the current frequency data as a byte array
  63013. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63014. * @returns a Uint8Array
  63015. */
  63016. Analyser.prototype.getByteFrequencyData = function () {
  63017. if (this._audioEngine.canUseWebAudio) {
  63018. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63019. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63020. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63021. }
  63022. return this._byteFreqs;
  63023. };
  63024. /**
  63025. * Gets the current waveform as a byte array
  63026. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63027. * @returns a Uint8Array
  63028. */
  63029. Analyser.prototype.getByteTimeDomainData = function () {
  63030. if (this._audioEngine.canUseWebAudio) {
  63031. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63032. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63033. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63034. }
  63035. return this._byteTime;
  63036. };
  63037. /**
  63038. * Gets the current frequency data as a float array
  63039. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63040. * @returns a Float32Array
  63041. */
  63042. Analyser.prototype.getFloatFrequencyData = function () {
  63043. if (this._audioEngine.canUseWebAudio) {
  63044. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63045. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63046. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63047. }
  63048. return this._floatFreqs;
  63049. };
  63050. /**
  63051. * Renders the debug canvas
  63052. */
  63053. Analyser.prototype.drawDebugCanvas = function () {
  63054. var _this = this;
  63055. if (this._audioEngine.canUseWebAudio) {
  63056. if (!this._debugCanvas) {
  63057. this._debugCanvas = document.createElement("canvas");
  63058. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63059. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63060. this._debugCanvas.style.position = "absolute";
  63061. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63062. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63063. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63064. document.body.appendChild(this._debugCanvas);
  63065. this._registerFunc = function () {
  63066. _this.drawDebugCanvas();
  63067. };
  63068. this._scene.registerBeforeRender(this._registerFunc);
  63069. }
  63070. if (this._registerFunc && this._debugCanvasContext) {
  63071. var workingArray = this.getByteFrequencyData();
  63072. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63073. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63074. // Draw the frequency domain chart.
  63075. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63076. var value = workingArray[i];
  63077. var percent = value / this.BARGRAPHAMPLITUDE;
  63078. var height = this.DEBUGCANVASSIZE.height * percent;
  63079. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63080. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63081. var hue = i / this.getFrequencyBinCount() * 360;
  63082. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63083. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63084. }
  63085. }
  63086. }
  63087. };
  63088. /**
  63089. * Stops rendering the debug canvas and removes it
  63090. */
  63091. Analyser.prototype.stopDebugCanvas = function () {
  63092. if (this._debugCanvas) {
  63093. if (this._registerFunc) {
  63094. this._scene.unregisterBeforeRender(this._registerFunc);
  63095. this._registerFunc = null;
  63096. }
  63097. document.body.removeChild(this._debugCanvas);
  63098. this._debugCanvas = null;
  63099. this._debugCanvasContext = null;
  63100. }
  63101. };
  63102. /**
  63103. * Connects two audio nodes
  63104. * @param inputAudioNode defines first node to connect
  63105. * @param outputAudioNode defines second node to connect
  63106. */
  63107. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63108. if (this._audioEngine.canUseWebAudio) {
  63109. inputAudioNode.connect(this._webAudioAnalyser);
  63110. this._webAudioAnalyser.connect(outputAudioNode);
  63111. }
  63112. };
  63113. /**
  63114. * Releases all associated resources
  63115. */
  63116. Analyser.prototype.dispose = function () {
  63117. if (this._audioEngine.canUseWebAudio) {
  63118. this._webAudioAnalyser.disconnect();
  63119. }
  63120. };
  63121. return Analyser;
  63122. }());
  63123. BABYLON.Analyser = Analyser;
  63124. })(BABYLON || (BABYLON = {}));
  63125. //# sourceMappingURL=babylon.analyser.js.map
  63126. var BABYLON;
  63127. (function (BABYLON) {
  63128. var CubeTexture = /** @class */ (function (_super) {
  63129. __extends(CubeTexture, _super);
  63130. /**
  63131. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63132. * as prefiltered data.
  63133. * @param rootUrl defines the url of the texture or the root name of the six images
  63134. * @param scene defines the scene the texture is attached to
  63135. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63136. * @param noMipmap defines if mipmaps should be created or not
  63137. * @param files defines the six files to load for the different faces
  63138. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63139. * @param onError defines a callback triggered in case of error during load
  63140. * @param format defines the internal format to use for the texture once loaded
  63141. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63142. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63143. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63144. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63145. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63146. * @return the cube texture
  63147. */
  63148. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63149. if (extensions === void 0) { extensions = null; }
  63150. if (noMipmap === void 0) { noMipmap = false; }
  63151. if (files === void 0) { files = null; }
  63152. if (onLoad === void 0) { onLoad = null; }
  63153. if (onError === void 0) { onError = null; }
  63154. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63155. if (prefiltered === void 0) { prefiltered = false; }
  63156. if (forcedExtension === void 0) { forcedExtension = null; }
  63157. if (createPolynomials === void 0) { createPolynomials = false; }
  63158. if (lodScale === void 0) { lodScale = 0.8; }
  63159. if (lodOffset === void 0) { lodOffset = 0; }
  63160. var _this = _super.call(this, scene) || this;
  63161. /**
  63162. * Gets or sets the center of the bounding box associated with the cube texture
  63163. * It must define where the camera used to render the texture was set
  63164. */
  63165. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63166. _this._rotationY = 0;
  63167. /** @hidden */
  63168. _this._prefiltered = false;
  63169. _this.name = rootUrl;
  63170. _this.url = rootUrl;
  63171. _this._noMipmap = noMipmap;
  63172. _this.hasAlpha = false;
  63173. _this._format = format;
  63174. _this.isCube = true;
  63175. _this._textureMatrix = BABYLON.Matrix.Identity();
  63176. _this._createPolynomials = createPolynomials;
  63177. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63178. if (!rootUrl && !files) {
  63179. return _this;
  63180. }
  63181. var lastDot = rootUrl.lastIndexOf(".");
  63182. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63183. var isDDS = (extension === ".dds");
  63184. var isEnv = (extension === ".env");
  63185. if (isEnv) {
  63186. _this.gammaSpace = false;
  63187. _this._prefiltered = false;
  63188. }
  63189. else {
  63190. _this._prefiltered = prefiltered;
  63191. if (prefiltered) {
  63192. _this.gammaSpace = false;
  63193. }
  63194. }
  63195. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63196. if (!files) {
  63197. if (!isEnv && !isDDS && !extensions) {
  63198. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63199. }
  63200. files = [];
  63201. if (extensions) {
  63202. for (var index = 0; index < extensions.length; index++) {
  63203. files.push(rootUrl + extensions[index]);
  63204. }
  63205. }
  63206. }
  63207. _this._files = files;
  63208. if (!_this._texture) {
  63209. if (!scene.useDelayedTextureLoading) {
  63210. if (prefiltered) {
  63211. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63212. }
  63213. else {
  63214. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63215. }
  63216. }
  63217. else {
  63218. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63219. }
  63220. }
  63221. else if (onLoad) {
  63222. if (_this._texture.isReady) {
  63223. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63224. }
  63225. else {
  63226. _this._texture.onLoadedObservable.add(onLoad);
  63227. }
  63228. }
  63229. return _this;
  63230. }
  63231. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63232. get: function () {
  63233. return this._boundingBoxSize;
  63234. },
  63235. /**
  63236. * Gets or sets the size of the bounding box associated with the cube texture
  63237. * When defined, the cubemap will switch to local mode
  63238. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63239. * @example https://www.babylonjs-playground.com/#RNASML
  63240. */
  63241. set: function (value) {
  63242. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63243. return;
  63244. }
  63245. this._boundingBoxSize = value;
  63246. var scene = this.getScene();
  63247. if (scene) {
  63248. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63249. }
  63250. },
  63251. enumerable: true,
  63252. configurable: true
  63253. });
  63254. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63255. /**
  63256. * Gets texture matrix rotation angle around Y axis radians.
  63257. */
  63258. get: function () {
  63259. return this._rotationY;
  63260. },
  63261. /**
  63262. * Sets texture matrix rotation angle around Y axis in radians.
  63263. */
  63264. set: function (value) {
  63265. this._rotationY = value;
  63266. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63267. },
  63268. enumerable: true,
  63269. configurable: true
  63270. });
  63271. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63272. var rootUrlKey = "";
  63273. files.forEach(function (url) { return rootUrlKey += url; });
  63274. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63275. };
  63276. /**
  63277. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63278. * @param url defines the url of the prefiltered texture
  63279. * @param scene defines the scene the texture is attached to
  63280. * @param forcedExtension defines the extension of the file if different from the url
  63281. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63282. * @return the prefiltered texture
  63283. */
  63284. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63285. if (forcedExtension === void 0) { forcedExtension = null; }
  63286. if (createPolynomials === void 0) { createPolynomials = true; }
  63287. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63288. };
  63289. // Methods
  63290. CubeTexture.prototype.delayLoad = function () {
  63291. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63292. return;
  63293. }
  63294. var scene = this.getScene();
  63295. if (!scene) {
  63296. return;
  63297. }
  63298. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63299. this._texture = this._getFromCache(this.url, this._noMipmap);
  63300. if (!this._texture) {
  63301. if (this._prefiltered) {
  63302. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63303. }
  63304. else {
  63305. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63306. }
  63307. }
  63308. };
  63309. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63310. return this._textureMatrix;
  63311. };
  63312. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63313. this._textureMatrix = value;
  63314. };
  63315. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63316. var texture = BABYLON.SerializationHelper.Parse(function () {
  63317. var prefiltered = false;
  63318. if (parsedTexture.prefiltered) {
  63319. prefiltered = parsedTexture.prefiltered;
  63320. }
  63321. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63322. }, parsedTexture, scene);
  63323. // Local Cubemaps
  63324. if (parsedTexture.boundingBoxPosition) {
  63325. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63326. }
  63327. if (parsedTexture.boundingBoxSize) {
  63328. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63329. }
  63330. // Animations
  63331. if (parsedTexture.animations) {
  63332. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63333. var parsedAnimation = parsedTexture.animations[animationIndex];
  63334. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63335. }
  63336. }
  63337. return texture;
  63338. };
  63339. CubeTexture.prototype.clone = function () {
  63340. var _this = this;
  63341. return BABYLON.SerializationHelper.Clone(function () {
  63342. var scene = _this.getScene();
  63343. if (!scene) {
  63344. return _this;
  63345. }
  63346. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63347. }, this);
  63348. };
  63349. __decorate([
  63350. BABYLON.serialize("rotationY")
  63351. ], CubeTexture.prototype, "_rotationY", void 0);
  63352. return CubeTexture;
  63353. }(BABYLON.BaseTexture));
  63354. BABYLON.CubeTexture = CubeTexture;
  63355. })(BABYLON || (BABYLON = {}));
  63356. //# sourceMappingURL=babylon.cubeTexture.js.map
  63357. var BABYLON;
  63358. (function (BABYLON) {
  63359. /**
  63360. * Raw cube texture where the raw buffers are passed in
  63361. */
  63362. var RawCubeTexture = /** @class */ (function (_super) {
  63363. __extends(RawCubeTexture, _super);
  63364. /**
  63365. * Creates a cube texture where the raw buffers are passed in.
  63366. * @param scene defines the scene the texture is attached to
  63367. * @param data defines the array of data to use to create each face
  63368. * @param size defines the size of the textures
  63369. * @param format defines the format of the data
  63370. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63371. * @param generateMipMaps defines if the engine should generate the mip levels
  63372. * @param invertY defines if data must be stored with Y axis inverted
  63373. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63374. * @param compression defines the compression used (null by default)
  63375. */
  63376. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63377. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63378. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63379. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63380. if (invertY === void 0) { invertY = false; }
  63381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63382. if (compression === void 0) { compression = null; }
  63383. var _this = _super.call(this, "", scene) || this;
  63384. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63385. return _this;
  63386. }
  63387. /**
  63388. * Updates the raw cube texture.
  63389. * @param data defines the data to store
  63390. * @param format defines the data format
  63391. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63392. * @param invertY defines if data must be stored with Y axis inverted
  63393. * @param compression defines the compression used (null by default)
  63394. * @param level defines which level of the texture to update
  63395. */
  63396. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63397. if (compression === void 0) { compression = null; }
  63398. if (level === void 0) { level = 0; }
  63399. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63400. };
  63401. /**
  63402. * Updates a raw cube texture with RGBD encoded data.
  63403. * @param data defines the array of data [mipmap][face] to use to create each face
  63404. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63405. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63406. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63407. * @returns a promsie that resolves when the operation is complete
  63408. */
  63409. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63410. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63411. if (lodScale === void 0) { lodScale = 0.8; }
  63412. if (lodOffset === void 0) { lodOffset = 0; }
  63413. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63414. };
  63415. /**
  63416. * Clones the raw cube texture.
  63417. * @return a new cube texture
  63418. */
  63419. RawCubeTexture.prototype.clone = function () {
  63420. var _this = this;
  63421. return BABYLON.SerializationHelper.Clone(function () {
  63422. var scene = _this.getScene();
  63423. var internalTexture = _this._texture;
  63424. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63425. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63426. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63427. }
  63428. return texture;
  63429. }, this);
  63430. };
  63431. /** @hidden */
  63432. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63433. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63434. internalTexture._bufferViewArrayArray = data;
  63435. internalTexture._lodGenerationScale = lodScale;
  63436. internalTexture._lodGenerationOffset = lodOffset;
  63437. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63438. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63439. internalTexture.isReady = true;
  63440. });
  63441. };
  63442. return RawCubeTexture;
  63443. }(BABYLON.CubeTexture));
  63444. BABYLON.RawCubeTexture = RawCubeTexture;
  63445. })(BABYLON || (BABYLON = {}));
  63446. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63447. var BABYLON;
  63448. (function (BABYLON) {
  63449. var RenderTargetTexture = /** @class */ (function (_super) {
  63450. __extends(RenderTargetTexture, _super);
  63451. /**
  63452. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63453. * or used a shadow, depth texture...
  63454. * @param name The friendly name of the texture
  63455. * @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)
  63456. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63457. * @param generateMipMaps True if mip maps need to be generated after render.
  63458. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63459. * @param type The type of the buffer in the RTT (int, half float, float...)
  63460. * @param isCube True if a cube texture needs to be created
  63461. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63462. * @param generateDepthBuffer True to generate a depth buffer
  63463. * @param generateStencilBuffer True to generate a stencil buffer
  63464. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63465. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63466. */
  63467. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63468. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63469. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63470. if (isCube === void 0) { isCube = false; }
  63471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63472. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63473. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63474. if (isMulti === void 0) { isMulti = false; }
  63475. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63476. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63477. _this.isCube = isCube;
  63478. /**
  63479. * Use this list to define the list of mesh you want to render.
  63480. */
  63481. _this.renderList = new Array();
  63482. _this.renderParticles = true;
  63483. _this.renderSprites = false;
  63484. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63485. _this.ignoreCameraViewport = false;
  63486. // Events
  63487. /**
  63488. * An event triggered when the texture is unbind.
  63489. */
  63490. _this.onBeforeBindObservable = new BABYLON.Observable();
  63491. /**
  63492. * An event triggered when the texture is unbind.
  63493. */
  63494. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63495. /**
  63496. * An event triggered before rendering the texture
  63497. */
  63498. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63499. /**
  63500. * An event triggered after rendering the texture
  63501. */
  63502. _this.onAfterRenderObservable = new BABYLON.Observable();
  63503. /**
  63504. * An event triggered after the texture clear
  63505. */
  63506. _this.onClearObservable = new BABYLON.Observable();
  63507. _this._currentRefreshId = -1;
  63508. _this._refreshRate = 1;
  63509. _this._samples = 1;
  63510. /**
  63511. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63512. * It must define where the camera used to render the texture is set
  63513. */
  63514. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63515. scene = _this.getScene();
  63516. if (!scene) {
  63517. return _this;
  63518. }
  63519. _this._engine = scene.getEngine();
  63520. _this.name = name;
  63521. _this.isRenderTarget = true;
  63522. _this._initialSizeParameter = size;
  63523. _this._processSizeParameter(size);
  63524. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63525. });
  63526. _this._generateMipMaps = generateMipMaps ? true : false;
  63527. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63528. // Rendering groups
  63529. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63530. if (isMulti) {
  63531. return _this;
  63532. }
  63533. _this._renderTargetOptions = {
  63534. generateMipMaps: generateMipMaps,
  63535. type: type,
  63536. format: format,
  63537. samplingMode: samplingMode,
  63538. generateDepthBuffer: generateDepthBuffer,
  63539. generateStencilBuffer: generateStencilBuffer
  63540. };
  63541. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63542. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63543. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63544. }
  63545. if (isCube) {
  63546. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63547. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63548. _this._textureMatrix = BABYLON.Matrix.Identity();
  63549. }
  63550. else {
  63551. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63552. }
  63553. return _this;
  63554. }
  63555. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63556. get: function () {
  63557. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63563. get: function () {
  63564. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63570. get: function () {
  63571. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63577. set: function (callback) {
  63578. if (this._onAfterUnbindObserver) {
  63579. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63580. }
  63581. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63582. },
  63583. enumerable: true,
  63584. configurable: true
  63585. });
  63586. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63587. set: function (callback) {
  63588. if (this._onBeforeRenderObserver) {
  63589. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63590. }
  63591. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63592. },
  63593. enumerable: true,
  63594. configurable: true
  63595. });
  63596. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63597. set: function (callback) {
  63598. if (this._onAfterRenderObserver) {
  63599. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63600. }
  63601. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63607. set: function (callback) {
  63608. if (this._onClearObserver) {
  63609. this.onClearObservable.remove(this._onClearObserver);
  63610. }
  63611. this._onClearObserver = this.onClearObservable.add(callback);
  63612. },
  63613. enumerable: true,
  63614. configurable: true
  63615. });
  63616. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63617. get: function () {
  63618. return this._renderTargetOptions;
  63619. },
  63620. enumerable: true,
  63621. configurable: true
  63622. });
  63623. RenderTargetTexture.prototype._onRatioRescale = function () {
  63624. if (this._sizeRatio) {
  63625. this.resize(this._initialSizeParameter);
  63626. }
  63627. };
  63628. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63629. get: function () {
  63630. return this._boundingBoxSize;
  63631. },
  63632. /**
  63633. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63634. * When defined, the cubemap will switch to local mode
  63635. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63636. * @example https://www.babylonjs-playground.com/#RNASML
  63637. */
  63638. set: function (value) {
  63639. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63640. return;
  63641. }
  63642. this._boundingBoxSize = value;
  63643. var scene = this.getScene();
  63644. if (scene) {
  63645. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63646. }
  63647. },
  63648. enumerable: true,
  63649. configurable: true
  63650. });
  63651. /**
  63652. * Creates a depth stencil texture.
  63653. * This is only available in WebGL 2 or with the depth texture extension available.
  63654. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63655. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63656. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63657. */
  63658. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63659. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63660. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63661. if (generateStencil === void 0) { generateStencil = false; }
  63662. if (!this.getScene()) {
  63663. return;
  63664. }
  63665. var engine = this.getScene().getEngine();
  63666. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63667. bilinearFiltering: bilinearFiltering,
  63668. comparisonFunction: comparisonFunction,
  63669. generateStencil: generateStencil,
  63670. isCube: this.isCube
  63671. });
  63672. engine.setFrameBufferDepthStencilTexture(this);
  63673. };
  63674. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63675. if (size.ratio) {
  63676. this._sizeRatio = size.ratio;
  63677. this._size = {
  63678. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63679. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63680. };
  63681. }
  63682. else {
  63683. this._size = size;
  63684. }
  63685. };
  63686. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63687. get: function () {
  63688. return this._samples;
  63689. },
  63690. set: function (value) {
  63691. if (this._samples === value) {
  63692. return;
  63693. }
  63694. var scene = this.getScene();
  63695. if (!scene) {
  63696. return;
  63697. }
  63698. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63699. },
  63700. enumerable: true,
  63701. configurable: true
  63702. });
  63703. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63704. this._currentRefreshId = -1;
  63705. };
  63706. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63707. get: function () {
  63708. return this._refreshRate;
  63709. },
  63710. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63711. set: function (value) {
  63712. this._refreshRate = value;
  63713. this.resetRefreshCounter();
  63714. },
  63715. enumerable: true,
  63716. configurable: true
  63717. });
  63718. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63719. if (!this._postProcessManager) {
  63720. var scene = this.getScene();
  63721. if (!scene) {
  63722. return;
  63723. }
  63724. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63725. this._postProcesses = new Array();
  63726. }
  63727. this._postProcesses.push(postProcess);
  63728. this._postProcesses[0].autoClear = false;
  63729. };
  63730. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63731. if (!this._postProcesses) {
  63732. return;
  63733. }
  63734. if (dispose) {
  63735. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63736. var postProcess = _a[_i];
  63737. postProcess.dispose();
  63738. }
  63739. }
  63740. this._postProcesses = [];
  63741. };
  63742. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63743. if (!this._postProcesses) {
  63744. return;
  63745. }
  63746. var index = this._postProcesses.indexOf(postProcess);
  63747. if (index === -1) {
  63748. return;
  63749. }
  63750. this._postProcesses.splice(index, 1);
  63751. if (this._postProcesses.length > 0) {
  63752. this._postProcesses[0].autoClear = false;
  63753. }
  63754. };
  63755. RenderTargetTexture.prototype._shouldRender = function () {
  63756. if (this._currentRefreshId === -1) { // At least render once
  63757. this._currentRefreshId = 1;
  63758. return true;
  63759. }
  63760. if (this.refreshRate === this._currentRefreshId) {
  63761. this._currentRefreshId = 1;
  63762. return true;
  63763. }
  63764. this._currentRefreshId++;
  63765. return false;
  63766. };
  63767. RenderTargetTexture.prototype.getRenderSize = function () {
  63768. if (this._size.width) {
  63769. return this._size.width;
  63770. }
  63771. return this._size;
  63772. };
  63773. RenderTargetTexture.prototype.getRenderWidth = function () {
  63774. if (this._size.width) {
  63775. return this._size.width;
  63776. }
  63777. return this._size;
  63778. };
  63779. RenderTargetTexture.prototype.getRenderHeight = function () {
  63780. if (this._size.width) {
  63781. return this._size.height;
  63782. }
  63783. return this._size;
  63784. };
  63785. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63786. get: function () {
  63787. return true;
  63788. },
  63789. enumerable: true,
  63790. configurable: true
  63791. });
  63792. RenderTargetTexture.prototype.scale = function (ratio) {
  63793. var newSize = this.getRenderSize() * ratio;
  63794. this.resize(newSize);
  63795. };
  63796. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63797. if (this.isCube) {
  63798. return this._textureMatrix;
  63799. }
  63800. return _super.prototype.getReflectionTextureMatrix.call(this);
  63801. };
  63802. RenderTargetTexture.prototype.resize = function (size) {
  63803. this.releaseInternalTexture();
  63804. var scene = this.getScene();
  63805. if (!scene) {
  63806. return;
  63807. }
  63808. this._processSizeParameter(size);
  63809. if (this.isCube) {
  63810. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63811. }
  63812. else {
  63813. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63814. }
  63815. };
  63816. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63817. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63818. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63819. var scene = this.getScene();
  63820. if (!scene) {
  63821. return;
  63822. }
  63823. var engine = scene.getEngine();
  63824. if (this.useCameraPostProcesses !== undefined) {
  63825. useCameraPostProcess = this.useCameraPostProcesses;
  63826. }
  63827. if (this._waitingRenderList) {
  63828. this.renderList = [];
  63829. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63830. var id = this._waitingRenderList[index];
  63831. var mesh_1 = scene.getMeshByID(id);
  63832. if (mesh_1) {
  63833. this.renderList.push(mesh_1);
  63834. }
  63835. }
  63836. delete this._waitingRenderList;
  63837. }
  63838. // Is predicate defined?
  63839. if (this.renderListPredicate) {
  63840. if (this.renderList) {
  63841. this.renderList.splice(0); // Clear previous renderList
  63842. }
  63843. else {
  63844. this.renderList = [];
  63845. }
  63846. var scene = this.getScene();
  63847. if (!scene) {
  63848. return;
  63849. }
  63850. var sceneMeshes = scene.meshes;
  63851. for (var index = 0; index < sceneMeshes.length; index++) {
  63852. var mesh = sceneMeshes[index];
  63853. if (this.renderListPredicate(mesh)) {
  63854. this.renderList.push(mesh);
  63855. }
  63856. }
  63857. }
  63858. this.onBeforeBindObservable.notifyObservers(this);
  63859. // Set custom projection.
  63860. // Needs to be before binding to prevent changing the aspect ratio.
  63861. var camera;
  63862. if (this.activeCamera) {
  63863. camera = this.activeCamera;
  63864. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63865. if (this.activeCamera !== scene.activeCamera) {
  63866. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63867. }
  63868. }
  63869. else {
  63870. camera = scene.activeCamera;
  63871. if (camera) {
  63872. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63873. }
  63874. }
  63875. // Prepare renderingManager
  63876. this._renderingManager.reset();
  63877. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63878. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63879. var sceneRenderId = scene.getRenderId();
  63880. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63881. var mesh = currentRenderList[meshIndex];
  63882. if (mesh) {
  63883. if (!mesh.isReady(this.refreshRate === 0)) {
  63884. this.resetRefreshCounter();
  63885. continue;
  63886. }
  63887. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63888. var isMasked = void 0;
  63889. if (!this.renderList && camera) {
  63890. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63891. }
  63892. else {
  63893. isMasked = false;
  63894. }
  63895. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63896. mesh._activate(sceneRenderId);
  63897. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63898. var subMesh = mesh.subMeshes[subIndex];
  63899. scene._activeIndices.addCount(subMesh.indexCount, false);
  63900. this._renderingManager.dispatch(subMesh, mesh);
  63901. }
  63902. }
  63903. }
  63904. }
  63905. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63906. var particleSystem = scene.particleSystems[particleIndex];
  63907. var emitter = particleSystem.emitter;
  63908. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63909. continue;
  63910. }
  63911. if (currentRenderList.indexOf(emitter) >= 0) {
  63912. this._renderingManager.dispatchParticles(particleSystem);
  63913. }
  63914. }
  63915. if (this.isCube) {
  63916. for (var face = 0; face < 6; face++) {
  63917. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63918. scene.incrementRenderId();
  63919. scene.resetCachedMaterial();
  63920. }
  63921. }
  63922. else {
  63923. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63924. }
  63925. this.onAfterUnbindObservable.notifyObservers(this);
  63926. if (scene.activeCamera) {
  63927. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63928. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63929. }
  63930. engine.setViewport(scene.activeCamera.viewport);
  63931. }
  63932. scene.resetCachedMaterial();
  63933. };
  63934. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63935. var minimum = 128;
  63936. var x = renderDimension * scale;
  63937. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63938. // Ensure we don't exceed the render dimension (while staying POT)
  63939. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63940. };
  63941. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63942. var _this = this;
  63943. if (!this._texture) {
  63944. return;
  63945. }
  63946. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63947. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63948. });
  63949. };
  63950. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63951. var scene = this.getScene();
  63952. if (!scene) {
  63953. return;
  63954. }
  63955. var engine = scene.getEngine();
  63956. if (!this._texture) {
  63957. return;
  63958. }
  63959. // Bind
  63960. if (this._postProcessManager) {
  63961. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63962. }
  63963. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63964. if (this._texture) {
  63965. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63966. }
  63967. }
  63968. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63969. // Clear
  63970. if (this.onClearObservable.hasObservers()) {
  63971. this.onClearObservable.notifyObservers(engine);
  63972. }
  63973. else {
  63974. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63975. }
  63976. if (!this._doNotChangeAspectRatio) {
  63977. scene.updateTransformMatrix(true);
  63978. }
  63979. // Render
  63980. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63981. if (this._postProcessManager) {
  63982. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63983. }
  63984. else if (useCameraPostProcess) {
  63985. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63986. }
  63987. if (!this._doNotChangeAspectRatio) {
  63988. scene.updateTransformMatrix(true);
  63989. }
  63990. // Dump ?
  63991. if (dumpForDebug) {
  63992. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63993. }
  63994. // Unbind
  63995. if (!this.isCube || faceIndex === 5) {
  63996. if (this.isCube) {
  63997. if (faceIndex === 5) {
  63998. engine.generateMipMapsForCubemap(this._texture);
  63999. }
  64000. }
  64001. this.unbindFrameBuffer(engine, faceIndex);
  64002. }
  64003. else {
  64004. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64005. }
  64006. };
  64007. /**
  64008. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64009. * This allowed control for front to back rendering or reversly depending of the special needs.
  64010. *
  64011. * @param renderingGroupId The rendering group id corresponding to its index
  64012. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64013. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64014. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64015. */
  64016. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64017. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64018. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64019. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64020. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64021. };
  64022. /**
  64023. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64024. *
  64025. * @param renderingGroupId The rendering group id corresponding to its index
  64026. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64027. */
  64028. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64029. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64030. };
  64031. RenderTargetTexture.prototype.clone = function () {
  64032. var textureSize = this.getSize();
  64033. 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);
  64034. // Base texture
  64035. newTexture.hasAlpha = this.hasAlpha;
  64036. newTexture.level = this.level;
  64037. // RenderTarget Texture
  64038. newTexture.coordinatesMode = this.coordinatesMode;
  64039. if (this.renderList) {
  64040. newTexture.renderList = this.renderList.slice(0);
  64041. }
  64042. return newTexture;
  64043. };
  64044. RenderTargetTexture.prototype.serialize = function () {
  64045. if (!this.name) {
  64046. return null;
  64047. }
  64048. var serializationObject = _super.prototype.serialize.call(this);
  64049. serializationObject.renderTargetSize = this.getRenderSize();
  64050. serializationObject.renderList = [];
  64051. if (this.renderList) {
  64052. for (var index = 0; index < this.renderList.length; index++) {
  64053. serializationObject.renderList.push(this.renderList[index].id);
  64054. }
  64055. }
  64056. return serializationObject;
  64057. };
  64058. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64059. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64060. var objBuffer = this.getInternalTexture();
  64061. var scene = this.getScene();
  64062. if (objBuffer && scene) {
  64063. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64064. }
  64065. };
  64066. RenderTargetTexture.prototype.dispose = function () {
  64067. if (this._postProcessManager) {
  64068. this._postProcessManager.dispose();
  64069. this._postProcessManager = null;
  64070. }
  64071. this.clearPostProcesses(true);
  64072. if (this._resizeObserver) {
  64073. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64074. this._resizeObserver = null;
  64075. }
  64076. this.renderList = null;
  64077. // Remove from custom render targets
  64078. var scene = this.getScene();
  64079. if (!scene) {
  64080. return;
  64081. }
  64082. var index = scene.customRenderTargets.indexOf(this);
  64083. if (index >= 0) {
  64084. scene.customRenderTargets.splice(index, 1);
  64085. }
  64086. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64087. var camera = _a[_i];
  64088. index = camera.customRenderTargets.indexOf(this);
  64089. if (index >= 0) {
  64090. camera.customRenderTargets.splice(index, 1);
  64091. }
  64092. }
  64093. _super.prototype.dispose.call(this);
  64094. };
  64095. RenderTargetTexture.prototype._rebuild = function () {
  64096. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64097. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64098. }
  64099. if (this._postProcessManager) {
  64100. this._postProcessManager._rebuild();
  64101. }
  64102. };
  64103. /**
  64104. * Clear the info related to rendering groups preventing retention point in material dispose.
  64105. */
  64106. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64107. if (this._renderingManager) {
  64108. this._renderingManager.freeRenderingGroups();
  64109. }
  64110. };
  64111. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64112. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64113. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64114. return RenderTargetTexture;
  64115. }(BABYLON.Texture));
  64116. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64117. })(BABYLON || (BABYLON = {}));
  64118. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64119. var BABYLON;
  64120. (function (BABYLON) {
  64121. ;
  64122. var MultiRenderTarget = /** @class */ (function (_super) {
  64123. __extends(MultiRenderTarget, _super);
  64124. function MultiRenderTarget(name, size, count, scene, options) {
  64125. var _this = this;
  64126. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64127. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64128. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64129. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64130. _this._engine = scene.getEngine();
  64131. if (!_this.isSupported) {
  64132. _this.dispose();
  64133. return;
  64134. }
  64135. var types = [];
  64136. var samplingModes = [];
  64137. for (var i = 0; i < count; i++) {
  64138. if (options && options.types && options.types[i] !== undefined) {
  64139. types.push(options.types[i]);
  64140. }
  64141. else {
  64142. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64143. }
  64144. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64145. samplingModes.push(options.samplingModes[i]);
  64146. }
  64147. else {
  64148. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64149. }
  64150. }
  64151. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64152. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64153. _this._size = size;
  64154. _this._multiRenderTargetOptions = {
  64155. samplingModes: samplingModes,
  64156. generateMipMaps: generateMipMaps,
  64157. generateDepthBuffer: generateDepthBuffer,
  64158. generateStencilBuffer: generateStencilBuffer,
  64159. generateDepthTexture: generateDepthTexture,
  64160. types: types,
  64161. textureCount: count
  64162. };
  64163. _this._createInternalTextures();
  64164. _this._createTextures();
  64165. return _this;
  64166. }
  64167. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64168. get: function () {
  64169. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64170. },
  64171. enumerable: true,
  64172. configurable: true
  64173. });
  64174. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64175. get: function () {
  64176. return this._textures;
  64177. },
  64178. enumerable: true,
  64179. configurable: true
  64180. });
  64181. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64182. get: function () {
  64183. return this._textures[this._textures.length - 1];
  64184. },
  64185. enumerable: true,
  64186. configurable: true
  64187. });
  64188. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64189. set: function (wrap) {
  64190. if (this._textures) {
  64191. for (var i = 0; i < this._textures.length; i++) {
  64192. this._textures[i].wrapU = wrap;
  64193. }
  64194. }
  64195. },
  64196. enumerable: true,
  64197. configurable: true
  64198. });
  64199. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64200. set: function (wrap) {
  64201. if (this._textures) {
  64202. for (var i = 0; i < this._textures.length; i++) {
  64203. this._textures[i].wrapV = wrap;
  64204. }
  64205. }
  64206. },
  64207. enumerable: true,
  64208. configurable: true
  64209. });
  64210. MultiRenderTarget.prototype._rebuild = function () {
  64211. this.releaseInternalTextures();
  64212. this._createInternalTextures();
  64213. for (var i = 0; i < this._internalTextures.length; i++) {
  64214. var texture = this._textures[i];
  64215. texture._texture = this._internalTextures[i];
  64216. }
  64217. // Keeps references to frame buffer and stencil/depth buffer
  64218. this._texture = this._internalTextures[0];
  64219. };
  64220. MultiRenderTarget.prototype._createInternalTextures = function () {
  64221. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64222. };
  64223. MultiRenderTarget.prototype._createTextures = function () {
  64224. this._textures = [];
  64225. for (var i = 0; i < this._internalTextures.length; i++) {
  64226. var texture = new BABYLON.Texture(null, this.getScene());
  64227. texture._texture = this._internalTextures[i];
  64228. this._textures.push(texture);
  64229. }
  64230. // Keeps references to frame buffer and stencil/depth buffer
  64231. this._texture = this._internalTextures[0];
  64232. };
  64233. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64234. get: function () {
  64235. return this._samples;
  64236. },
  64237. set: function (value) {
  64238. if (this._samples === value) {
  64239. return;
  64240. }
  64241. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64242. },
  64243. enumerable: true,
  64244. configurable: true
  64245. });
  64246. MultiRenderTarget.prototype.resize = function (size) {
  64247. this.releaseInternalTextures();
  64248. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64249. this._createInternalTextures();
  64250. };
  64251. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64252. var _this = this;
  64253. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64254. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64255. });
  64256. };
  64257. MultiRenderTarget.prototype.dispose = function () {
  64258. this.releaseInternalTextures();
  64259. _super.prototype.dispose.call(this);
  64260. };
  64261. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64262. if (!this._internalTextures) {
  64263. return;
  64264. }
  64265. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64266. if (this._internalTextures[i] !== undefined) {
  64267. this._internalTextures[i].dispose();
  64268. this._internalTextures.splice(i, 1);
  64269. }
  64270. }
  64271. };
  64272. return MultiRenderTarget;
  64273. }(BABYLON.RenderTargetTexture));
  64274. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64275. })(BABYLON || (BABYLON = {}));
  64276. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64277. var BABYLON;
  64278. (function (BABYLON) {
  64279. var MirrorTexture = /** @class */ (function (_super) {
  64280. __extends(MirrorTexture, _super);
  64281. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64282. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64284. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64285. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64286. _this.scene = scene;
  64287. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64288. _this._transformMatrix = BABYLON.Matrix.Zero();
  64289. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64290. _this._adaptiveBlurKernel = 0;
  64291. _this._blurKernelX = 0;
  64292. _this._blurKernelY = 0;
  64293. _this._blurRatio = 1.0;
  64294. _this.ignoreCameraViewport = true;
  64295. _this._updateGammaSpace();
  64296. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64297. _this._updateGammaSpace;
  64298. });
  64299. _this.onBeforeRenderObservable.add(function () {
  64300. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64301. _this._savedViewMatrix = scene.getViewMatrix();
  64302. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64303. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64304. scene.clipPlane = _this.mirrorPlane;
  64305. scene.getEngine().cullBackFaces = false;
  64306. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64307. });
  64308. _this.onAfterRenderObservable.add(function () {
  64309. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64310. scene.getEngine().cullBackFaces = true;
  64311. scene._mirroredCameraPosition = null;
  64312. delete scene.clipPlane;
  64313. });
  64314. return _this;
  64315. }
  64316. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64317. get: function () {
  64318. return this._blurRatio;
  64319. },
  64320. set: function (value) {
  64321. if (this._blurRatio === value) {
  64322. return;
  64323. }
  64324. this._blurRatio = value;
  64325. this._preparePostProcesses();
  64326. },
  64327. enumerable: true,
  64328. configurable: true
  64329. });
  64330. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64331. set: function (value) {
  64332. this._adaptiveBlurKernel = value;
  64333. this._autoComputeBlurKernel();
  64334. },
  64335. enumerable: true,
  64336. configurable: true
  64337. });
  64338. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64339. set: function (value) {
  64340. this.blurKernelX = value;
  64341. this.blurKernelY = value;
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64347. get: function () {
  64348. return this._blurKernelX;
  64349. },
  64350. set: function (value) {
  64351. if (this._blurKernelX === value) {
  64352. return;
  64353. }
  64354. this._blurKernelX = value;
  64355. this._preparePostProcesses();
  64356. },
  64357. enumerable: true,
  64358. configurable: true
  64359. });
  64360. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64361. get: function () {
  64362. return this._blurKernelY;
  64363. },
  64364. set: function (value) {
  64365. if (this._blurKernelY === value) {
  64366. return;
  64367. }
  64368. this._blurKernelY = value;
  64369. this._preparePostProcesses();
  64370. },
  64371. enumerable: true,
  64372. configurable: true
  64373. });
  64374. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64375. var engine = this.getScene().getEngine();
  64376. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64377. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64378. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64379. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64380. };
  64381. MirrorTexture.prototype._onRatioRescale = function () {
  64382. if (this._sizeRatio) {
  64383. this.resize(this._initialSizeParameter);
  64384. if (!this._adaptiveBlurKernel) {
  64385. this._preparePostProcesses();
  64386. }
  64387. }
  64388. if (this._adaptiveBlurKernel) {
  64389. this._autoComputeBlurKernel();
  64390. }
  64391. };
  64392. MirrorTexture.prototype._updateGammaSpace = function () {
  64393. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64394. };
  64395. MirrorTexture.prototype._preparePostProcesses = function () {
  64396. this.clearPostProcesses(true);
  64397. if (this._blurKernelX && this._blurKernelY) {
  64398. var engine = this.getScene().getEngine();
  64399. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64400. 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);
  64401. this._blurX.autoClear = false;
  64402. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64403. this._blurX.inputTexture = this._texture;
  64404. }
  64405. else {
  64406. this._blurX.alwaysForcePOT = true;
  64407. }
  64408. 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);
  64409. this._blurY.autoClear = false;
  64410. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64411. this.addPostProcess(this._blurX);
  64412. this.addPostProcess(this._blurY);
  64413. }
  64414. else {
  64415. if (this._blurY) {
  64416. this.removePostProcess(this._blurY);
  64417. this._blurY.dispose();
  64418. this._blurY = null;
  64419. }
  64420. if (this._blurX) {
  64421. this.removePostProcess(this._blurX);
  64422. this._blurX.dispose();
  64423. this._blurX = null;
  64424. }
  64425. }
  64426. };
  64427. MirrorTexture.prototype.clone = function () {
  64428. var scene = this.getScene();
  64429. if (!scene) {
  64430. return this;
  64431. }
  64432. var textureSize = this.getSize();
  64433. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64434. // Base texture
  64435. newTexture.hasAlpha = this.hasAlpha;
  64436. newTexture.level = this.level;
  64437. // Mirror Texture
  64438. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64439. if (this.renderList) {
  64440. newTexture.renderList = this.renderList.slice(0);
  64441. }
  64442. return newTexture;
  64443. };
  64444. MirrorTexture.prototype.serialize = function () {
  64445. if (!this.name) {
  64446. return null;
  64447. }
  64448. var serializationObject = _super.prototype.serialize.call(this);
  64449. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64450. return serializationObject;
  64451. };
  64452. MirrorTexture.prototype.dispose = function () {
  64453. _super.prototype.dispose.call(this);
  64454. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64455. };
  64456. return MirrorTexture;
  64457. }(BABYLON.RenderTargetTexture));
  64458. BABYLON.MirrorTexture = MirrorTexture;
  64459. })(BABYLON || (BABYLON = {}));
  64460. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64461. var BABYLON;
  64462. (function (BABYLON) {
  64463. /**
  64464. * Creates a refraction texture used by refraction channel of the standard material.
  64465. * @param name the texture name
  64466. * @param size size of the underlying texture
  64467. * @param scene root scene
  64468. */
  64469. var RefractionTexture = /** @class */ (function (_super) {
  64470. __extends(RefractionTexture, _super);
  64471. function RefractionTexture(name, size, scene, generateMipMaps) {
  64472. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64473. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64474. _this.depth = 2.0;
  64475. _this.onBeforeRenderObservable.add(function () {
  64476. scene.clipPlane = _this.refractionPlane;
  64477. });
  64478. _this.onAfterRenderObservable.add(function () {
  64479. delete scene.clipPlane;
  64480. });
  64481. return _this;
  64482. }
  64483. RefractionTexture.prototype.clone = function () {
  64484. var scene = this.getScene();
  64485. if (!scene) {
  64486. return this;
  64487. }
  64488. var textureSize = this.getSize();
  64489. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64490. // Base texture
  64491. newTexture.hasAlpha = this.hasAlpha;
  64492. newTexture.level = this.level;
  64493. // Refraction Texture
  64494. newTexture.refractionPlane = this.refractionPlane.clone();
  64495. if (this.renderList) {
  64496. newTexture.renderList = this.renderList.slice(0);
  64497. }
  64498. newTexture.depth = this.depth;
  64499. return newTexture;
  64500. };
  64501. RefractionTexture.prototype.serialize = function () {
  64502. if (!this.name) {
  64503. return null;
  64504. }
  64505. var serializationObject = _super.prototype.serialize.call(this);
  64506. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64507. serializationObject.depth = this.depth;
  64508. return serializationObject;
  64509. };
  64510. return RefractionTexture;
  64511. }(BABYLON.RenderTargetTexture));
  64512. BABYLON.RefractionTexture = RefractionTexture;
  64513. })(BABYLON || (BABYLON = {}));
  64514. //# sourceMappingURL=babylon.refractionTexture.js.map
  64515. var BABYLON;
  64516. (function (BABYLON) {
  64517. /**
  64518. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64519. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64520. */
  64521. var DynamicTexture = /** @class */ (function (_super) {
  64522. __extends(DynamicTexture, _super);
  64523. /**
  64524. * Creates a {BABYLON.DynamicTexture}
  64525. * @param name defines the name of the texture
  64526. * @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
  64527. * @param scene defines the scene where you want the texture
  64528. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64529. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64530. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64531. */
  64532. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64533. if (scene === void 0) { scene = null; }
  64534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64535. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64536. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64537. _this.name = name;
  64538. _this._engine = _this.getScene().getEngine();
  64539. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64540. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64541. _this._generateMipMaps = generateMipMaps;
  64542. if (options.getContext) {
  64543. _this._canvas = options;
  64544. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64545. }
  64546. else {
  64547. _this._canvas = document.createElement("canvas");
  64548. if (options.width || options.width === 0) {
  64549. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64550. }
  64551. else {
  64552. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64553. }
  64554. }
  64555. var textureSize = _this.getSize();
  64556. _this._canvas.width = textureSize.width;
  64557. _this._canvas.height = textureSize.height;
  64558. _this._context = _this._canvas.getContext("2d");
  64559. return _this;
  64560. }
  64561. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64562. /**
  64563. * Gets the current state of canRescale
  64564. */
  64565. get: function () {
  64566. return true;
  64567. },
  64568. enumerable: true,
  64569. configurable: true
  64570. });
  64571. DynamicTexture.prototype._recreate = function (textureSize) {
  64572. this._canvas.width = textureSize.width;
  64573. this._canvas.height = textureSize.height;
  64574. this.releaseInternalTexture();
  64575. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64576. };
  64577. /**
  64578. * Scales the texture
  64579. * @param ratio the scale factor to apply to both width and height
  64580. */
  64581. DynamicTexture.prototype.scale = function (ratio) {
  64582. var textureSize = this.getSize();
  64583. textureSize.width *= ratio;
  64584. textureSize.height *= ratio;
  64585. this._recreate(textureSize);
  64586. };
  64587. /**
  64588. * Resizes the texture
  64589. * @param width the new width
  64590. * @param height the new height
  64591. */
  64592. DynamicTexture.prototype.scaleTo = function (width, height) {
  64593. var textureSize = this.getSize();
  64594. textureSize.width = width;
  64595. textureSize.height = height;
  64596. this._recreate(textureSize);
  64597. };
  64598. /**
  64599. * Gets the context of the canvas used by the texture
  64600. * @returns the canvas context of the dynamic texture
  64601. */
  64602. DynamicTexture.prototype.getContext = function () {
  64603. return this._context;
  64604. };
  64605. /**
  64606. * Clears the texture
  64607. */
  64608. DynamicTexture.prototype.clear = function () {
  64609. var size = this.getSize();
  64610. this._context.fillRect(0, 0, size.width, size.height);
  64611. };
  64612. /**
  64613. * Updates the texture
  64614. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64615. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64616. */
  64617. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64618. if (premulAlpha === void 0) { premulAlpha = false; }
  64619. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64620. };
  64621. /**
  64622. * Draws text onto the texture
  64623. * @param text defines the text to be drawn
  64624. * @param x defines the placement of the text from the left
  64625. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64626. * @param font defines the font to be used with font-style, font-size, font-name
  64627. * @param color defines the color used for the text
  64628. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64629. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64630. * @param update defines whether texture is immediately update (default is true)
  64631. */
  64632. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64633. if (update === void 0) { update = true; }
  64634. var size = this.getSize();
  64635. if (clearColor) {
  64636. this._context.fillStyle = clearColor;
  64637. this._context.fillRect(0, 0, size.width, size.height);
  64638. }
  64639. this._context.font = font;
  64640. if (x === null || x === undefined) {
  64641. var textSize = this._context.measureText(text);
  64642. x = (size.width - textSize.width) / 2;
  64643. }
  64644. if (y === null || y === undefined) {
  64645. var fontSize = parseInt((font.replace(/\D/g, '')));
  64646. y = (size.height / 2) + (fontSize / 3.65);
  64647. }
  64648. this._context.fillStyle = color;
  64649. this._context.fillText(text, x, y);
  64650. if (update) {
  64651. this.update(invertY);
  64652. }
  64653. };
  64654. /**
  64655. * Clones the texture
  64656. * @returns the clone of the texture.
  64657. */
  64658. DynamicTexture.prototype.clone = function () {
  64659. var scene = this.getScene();
  64660. if (!scene) {
  64661. return this;
  64662. }
  64663. var textureSize = this.getSize();
  64664. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64665. // Base texture
  64666. newTexture.hasAlpha = this.hasAlpha;
  64667. newTexture.level = this.level;
  64668. // Dynamic Texture
  64669. newTexture.wrapU = this.wrapU;
  64670. newTexture.wrapV = this.wrapV;
  64671. return newTexture;
  64672. };
  64673. /** @hidden */
  64674. DynamicTexture.prototype._rebuild = function () {
  64675. this.update();
  64676. };
  64677. return DynamicTexture;
  64678. }(BABYLON.Texture));
  64679. BABYLON.DynamicTexture = DynamicTexture;
  64680. })(BABYLON || (BABYLON = {}));
  64681. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64682. var BABYLON;
  64683. (function (BABYLON) {
  64684. var VideoTexture = /** @class */ (function (_super) {
  64685. __extends(VideoTexture, _super);
  64686. /**
  64687. * Creates a video texture.
  64688. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64689. * @param {string | null} name optional name, will detect from video source, if not defined
  64690. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64691. * @param {BABYLON.Scene} scene is obviously the current scene.
  64692. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64693. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64694. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64695. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64696. */
  64697. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64698. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64699. if (invertY === void 0) { invertY = false; }
  64700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64701. if (settings === void 0) { settings = {
  64702. autoPlay: true,
  64703. loop: true,
  64704. autoUpdateTexture: true,
  64705. }; }
  64706. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64707. _this._onUserActionRequestedObservable = null;
  64708. _this._stillImageCaptured = false;
  64709. _this._poster = false;
  64710. _this._createInternalTexture = function () {
  64711. if (_this._texture != null) {
  64712. if (_this._poster) {
  64713. _this._texture.dispose();
  64714. _this._poster = false;
  64715. }
  64716. else {
  64717. return;
  64718. }
  64719. }
  64720. if (!_this._engine.needPOTTextures ||
  64721. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64722. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64723. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64724. }
  64725. else {
  64726. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64727. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64728. _this._generateMipMaps = false;
  64729. }
  64730. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64731. if (!_this.video.autoplay) {
  64732. var oldHandler_1 = _this.video.onplaying;
  64733. var error_1 = false;
  64734. _this.video.onplaying = function () {
  64735. _this.video.onplaying = oldHandler_1;
  64736. _this._texture.isReady = true;
  64737. _this._updateInternalTexture();
  64738. if (!error_1) {
  64739. _this.video.pause();
  64740. }
  64741. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64742. _this.onLoadObservable.notifyObservers(_this);
  64743. }
  64744. };
  64745. var playing = _this.video.play();
  64746. if (playing) {
  64747. playing.then(function () {
  64748. // Everything is good.
  64749. })
  64750. .catch(function () {
  64751. error_1 = true;
  64752. // On Chrome for instance, new policies might prevent playing without user interaction.
  64753. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64754. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64755. }
  64756. });
  64757. }
  64758. else {
  64759. _this.video.onplaying = oldHandler_1;
  64760. _this._texture.isReady = true;
  64761. _this._updateInternalTexture();
  64762. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64763. _this.onLoadObservable.notifyObservers(_this);
  64764. }
  64765. }
  64766. }
  64767. else {
  64768. _this._texture.isReady = true;
  64769. _this._updateInternalTexture();
  64770. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64771. _this.onLoadObservable.notifyObservers(_this);
  64772. }
  64773. }
  64774. };
  64775. _this.reset = function () {
  64776. if (_this._texture == null) {
  64777. return;
  64778. }
  64779. if (!_this._poster) {
  64780. _this._texture.dispose();
  64781. _this._texture = null;
  64782. }
  64783. };
  64784. _this._updateInternalTexture = function (e) {
  64785. if (_this._texture == null || !_this._texture.isReady) {
  64786. return;
  64787. }
  64788. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64789. return;
  64790. }
  64791. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64792. };
  64793. _this._engine = _this.getScene().getEngine();
  64794. _this._generateMipMaps = generateMipMaps;
  64795. _this._samplingMode = samplingMode;
  64796. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64797. _this.name = name || _this._getName(src);
  64798. _this.video = _this._getVideo(src);
  64799. if (settings.poster) {
  64800. _this.video.poster = settings.poster;
  64801. }
  64802. if (settings.autoPlay !== undefined) {
  64803. _this.video.autoplay = settings.autoPlay;
  64804. }
  64805. if (settings.loop !== undefined) {
  64806. _this.video.loop = settings.loop;
  64807. }
  64808. _this.video.setAttribute("playsinline", "");
  64809. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64810. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64811. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64812. _this.video.addEventListener("emptied", _this.reset);
  64813. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64814. _this._createInternalTexture();
  64815. }
  64816. if (settings.poster) {
  64817. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  64818. _this._poster = true;
  64819. }
  64820. return _this;
  64821. }
  64822. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64823. get: function () {
  64824. if (!this._onUserActionRequestedObservable) {
  64825. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64826. }
  64827. return this._onUserActionRequestedObservable;
  64828. },
  64829. enumerable: true,
  64830. configurable: true
  64831. });
  64832. VideoTexture.prototype._getName = function (src) {
  64833. if (src instanceof HTMLVideoElement) {
  64834. return src.currentSrc;
  64835. }
  64836. if (typeof src === "object") {
  64837. return src.toString();
  64838. }
  64839. return src;
  64840. };
  64841. ;
  64842. VideoTexture.prototype._getVideo = function (src) {
  64843. if (src instanceof HTMLVideoElement) {
  64844. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64845. return src;
  64846. }
  64847. var video = document.createElement("video");
  64848. if (typeof src === "string") {
  64849. BABYLON.Tools.SetCorsBehavior(src, video);
  64850. video.src = src;
  64851. }
  64852. else {
  64853. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64854. src.forEach(function (url) {
  64855. var source = document.createElement("source");
  64856. source.src = url;
  64857. video.appendChild(source);
  64858. });
  64859. }
  64860. return video;
  64861. };
  64862. ;
  64863. /**
  64864. * Internal method to initiate `update`.
  64865. */
  64866. VideoTexture.prototype._rebuild = function () {
  64867. this.update();
  64868. };
  64869. /**
  64870. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64871. */
  64872. VideoTexture.prototype.update = function () {
  64873. if (!this.autoUpdateTexture) {
  64874. // Expecting user to call `updateTexture` manually
  64875. return;
  64876. }
  64877. this.updateTexture(true);
  64878. };
  64879. /**
  64880. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64881. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64882. */
  64883. VideoTexture.prototype.updateTexture = function (isVisible) {
  64884. if (!isVisible) {
  64885. return;
  64886. }
  64887. if (this.video.paused && this._stillImageCaptured) {
  64888. return;
  64889. }
  64890. this._stillImageCaptured = true;
  64891. this._updateInternalTexture();
  64892. };
  64893. /**
  64894. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64895. * @param url New url.
  64896. */
  64897. VideoTexture.prototype.updateURL = function (url) {
  64898. this.video.src = url;
  64899. };
  64900. VideoTexture.prototype.dispose = function () {
  64901. _super.prototype.dispose.call(this);
  64902. if (this._onUserActionRequestedObservable) {
  64903. this._onUserActionRequestedObservable.clear();
  64904. this._onUserActionRequestedObservable = null;
  64905. }
  64906. this.video.removeEventListener("canplay", this._createInternalTexture);
  64907. this.video.removeEventListener("paused", this._updateInternalTexture);
  64908. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64909. this.video.removeEventListener("emptied", this.reset);
  64910. this.video.pause();
  64911. };
  64912. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64913. var video = document.createElement("video");
  64914. video.setAttribute('autoplay', '');
  64915. video.setAttribute('muted', '');
  64916. video.setAttribute('playsinline', '');
  64917. var constraintsDeviceId;
  64918. if (constraints && constraints.deviceId) {
  64919. constraintsDeviceId = {
  64920. exact: constraints.deviceId,
  64921. };
  64922. }
  64923. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64924. if (navigator.mediaDevices) {
  64925. navigator.mediaDevices.getUserMedia({ video: constraints })
  64926. .then(function (stream) {
  64927. if (video.mozSrcObject !== undefined) {
  64928. // hack for Firefox < 19
  64929. video.mozSrcObject = stream;
  64930. }
  64931. else {
  64932. video.srcObject = stream;
  64933. }
  64934. var onPlaying = function () {
  64935. if (onReady) {
  64936. onReady(new VideoTexture("video", video, scene, true, true));
  64937. }
  64938. video.removeEventListener("playing", onPlaying);
  64939. };
  64940. video.addEventListener("playing", onPlaying);
  64941. video.play();
  64942. })
  64943. .catch(function (err) {
  64944. BABYLON.Tools.Error(err.name);
  64945. });
  64946. }
  64947. else {
  64948. navigator.getUserMedia =
  64949. navigator.getUserMedia ||
  64950. navigator.webkitGetUserMedia ||
  64951. navigator.mozGetUserMedia ||
  64952. navigator.msGetUserMedia;
  64953. if (navigator.getUserMedia) {
  64954. navigator.getUserMedia({
  64955. video: {
  64956. deviceId: constraintsDeviceId,
  64957. width: {
  64958. min: (constraints && constraints.minWidth) || 256,
  64959. max: (constraints && constraints.maxWidth) || 640,
  64960. },
  64961. height: {
  64962. min: (constraints && constraints.minHeight) || 256,
  64963. max: (constraints && constraints.maxHeight) || 480,
  64964. },
  64965. },
  64966. }, function (stream) {
  64967. if (video.mozSrcObject !== undefined) {
  64968. // hack for Firefox < 19
  64969. video.mozSrcObject = stream;
  64970. }
  64971. else {
  64972. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64973. }
  64974. video.play();
  64975. if (onReady) {
  64976. onReady(new VideoTexture("video", video, scene, true, true));
  64977. }
  64978. }, function (e) {
  64979. BABYLON.Tools.Error(e.name);
  64980. });
  64981. }
  64982. }
  64983. };
  64984. return VideoTexture;
  64985. }(BABYLON.Texture));
  64986. BABYLON.VideoTexture = VideoTexture;
  64987. })(BABYLON || (BABYLON = {}));
  64988. //# sourceMappingURL=babylon.videoTexture.js.map
  64989. var BABYLON;
  64990. (function (BABYLON) {
  64991. var RawTexture = /** @class */ (function (_super) {
  64992. __extends(RawTexture, _super);
  64993. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64994. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64995. if (invertY === void 0) { invertY = false; }
  64996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64997. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64998. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64999. _this.format = format;
  65000. _this._engine = scene.getEngine();
  65001. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65002. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65003. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65004. return _this;
  65005. }
  65006. RawTexture.prototype.update = function (data) {
  65007. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65008. };
  65009. // Statics
  65010. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65012. if (invertY === void 0) { invertY = false; }
  65013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65015. };
  65016. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65017. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65018. if (invertY === void 0) { invertY = false; }
  65019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65020. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65021. };
  65022. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65023. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65024. if (invertY === void 0) { invertY = false; }
  65025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65026. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65027. };
  65028. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65029. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65030. if (invertY === void 0) { invertY = false; }
  65031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65032. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65033. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65034. };
  65035. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65036. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65037. if (invertY === void 0) { invertY = false; }
  65038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65039. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65040. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65041. };
  65042. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65044. if (invertY === void 0) { invertY = false; }
  65045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65046. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65047. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65048. };
  65049. return RawTexture;
  65050. }(BABYLON.Texture));
  65051. BABYLON.RawTexture = RawTexture;
  65052. })(BABYLON || (BABYLON = {}));
  65053. //# sourceMappingURL=babylon.rawTexture.js.map
  65054. var BABYLON;
  65055. (function (BABYLON) {
  65056. /**
  65057. * Class used to store 3D textures containing user data
  65058. */
  65059. var RawTexture3D = /** @class */ (function (_super) {
  65060. __extends(RawTexture3D, _super);
  65061. /**
  65062. * Create a new RawTexture3D
  65063. * @param data defines the data of the texture
  65064. * @param width defines the width of the texture
  65065. * @param height defines the height of the texture
  65066. * @param depth defines the depth of the texture
  65067. * @param format defines the texture format to use
  65068. * @param scene defines the hosting scene
  65069. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65070. * @param invertY defines if texture must be stored with Y axis inverted
  65071. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65072. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65073. */
  65074. function RawTexture3D(data, width, height, depth,
  65075. /** Gets or sets the texture format to use */
  65076. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65078. if (invertY === void 0) { invertY = false; }
  65079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65080. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65081. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65082. _this.format = format;
  65083. _this._engine = scene.getEngine();
  65084. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65085. _this.is3D = true;
  65086. return _this;
  65087. }
  65088. /**
  65089. * Update the texture with new data
  65090. * @param data defines the data to store in the texture
  65091. */
  65092. RawTexture3D.prototype.update = function (data) {
  65093. if (!this._texture) {
  65094. return;
  65095. }
  65096. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65097. };
  65098. return RawTexture3D;
  65099. }(BABYLON.Texture));
  65100. BABYLON.RawTexture3D = RawTexture3D;
  65101. })(BABYLON || (BABYLON = {}));
  65102. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65103. var BABYLON;
  65104. (function (BABYLON) {
  65105. /**
  65106. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65107. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65108. */
  65109. var PostProcessManager = /** @class */ (function () {
  65110. /**
  65111. * Creates a new instance PostProcess
  65112. * @param scene The scene that the post process is associated with.
  65113. */
  65114. function PostProcessManager(scene) {
  65115. this._vertexBuffers = {};
  65116. this._scene = scene;
  65117. }
  65118. PostProcessManager.prototype._prepareBuffers = function () {
  65119. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65120. return;
  65121. }
  65122. // VBO
  65123. var vertices = [];
  65124. vertices.push(1, 1);
  65125. vertices.push(-1, 1);
  65126. vertices.push(-1, -1);
  65127. vertices.push(1, -1);
  65128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65129. this._buildIndexBuffer();
  65130. };
  65131. PostProcessManager.prototype._buildIndexBuffer = function () {
  65132. // Indices
  65133. var indices = [];
  65134. indices.push(0);
  65135. indices.push(1);
  65136. indices.push(2);
  65137. indices.push(0);
  65138. indices.push(2);
  65139. indices.push(3);
  65140. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65141. };
  65142. /**
  65143. * Rebuilds the vertex buffers of the manager.
  65144. */
  65145. PostProcessManager.prototype._rebuild = function () {
  65146. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65147. if (!vb) {
  65148. return;
  65149. }
  65150. vb._rebuild();
  65151. this._buildIndexBuffer();
  65152. };
  65153. // Methods
  65154. /**
  65155. * Prepares a frame to be run through a post process.
  65156. * @param sourceTexture The input texture to the post procesess. (default: null)
  65157. * @param postProcesses An array of post processes to be run. (default: null)
  65158. * @returns True if the post processes were able to be run.
  65159. */
  65160. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65161. if (sourceTexture === void 0) { sourceTexture = null; }
  65162. if (postProcesses === void 0) { postProcesses = null; }
  65163. var camera = this._scene.activeCamera;
  65164. if (!camera) {
  65165. return false;
  65166. }
  65167. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65168. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65169. return false;
  65170. }
  65171. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65172. return true;
  65173. };
  65174. /**
  65175. * Manually render a set of post processes to a texture.
  65176. * @param postProcesses An array of post processes to be run.
  65177. * @param targetTexture The target texture to render to.
  65178. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65179. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65180. * @param lodLevel defines which lod of the texture to render to
  65181. */
  65182. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65183. if (targetTexture === void 0) { targetTexture = null; }
  65184. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65185. if (faceIndex === void 0) { faceIndex = 0; }
  65186. if (lodLevel === void 0) { lodLevel = 0; }
  65187. var engine = this._scene.getEngine();
  65188. for (var index = 0; index < postProcesses.length; index++) {
  65189. if (index < postProcesses.length - 1) {
  65190. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65191. }
  65192. else {
  65193. if (targetTexture) {
  65194. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65195. }
  65196. else {
  65197. engine.restoreDefaultFramebuffer();
  65198. }
  65199. }
  65200. var pp = postProcesses[index];
  65201. var effect = pp.apply();
  65202. if (effect) {
  65203. pp.onBeforeRenderObservable.notifyObservers(effect);
  65204. // VBOs
  65205. this._prepareBuffers();
  65206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65207. // Draw order
  65208. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65209. pp.onAfterRenderObservable.notifyObservers(effect);
  65210. }
  65211. }
  65212. // Restore depth buffer
  65213. engine.setDepthBuffer(true);
  65214. engine.setDepthWrite(true);
  65215. };
  65216. /**
  65217. * Finalize the result of the output of the postprocesses.
  65218. * @param doNotPresent If true the result will not be displayed to the screen.
  65219. * @param targetTexture The target texture to render to.
  65220. * @param faceIndex The index of the face to bind the target texture to.
  65221. * @param postProcesses The array of post processes to render.
  65222. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65223. */
  65224. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65225. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65226. var camera = this._scene.activeCamera;
  65227. if (!camera) {
  65228. return;
  65229. }
  65230. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65231. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65232. return;
  65233. }
  65234. var engine = this._scene.getEngine();
  65235. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65236. var pp = postProcesses[index];
  65237. if (index < len - 1) {
  65238. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65239. }
  65240. else {
  65241. if (targetTexture) {
  65242. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65243. pp._outputTexture = targetTexture;
  65244. }
  65245. else {
  65246. engine.restoreDefaultFramebuffer();
  65247. pp._outputTexture = null;
  65248. }
  65249. }
  65250. if (doNotPresent) {
  65251. break;
  65252. }
  65253. var effect = pp.apply();
  65254. if (effect) {
  65255. pp.onBeforeRenderObservable.notifyObservers(effect);
  65256. // VBOs
  65257. this._prepareBuffers();
  65258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65259. // Draw order
  65260. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65261. pp.onAfterRenderObservable.notifyObservers(effect);
  65262. }
  65263. }
  65264. // Restore states
  65265. engine.setDepthBuffer(true);
  65266. engine.setDepthWrite(true);
  65267. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65268. };
  65269. /**
  65270. * Disposes of the post process manager.
  65271. */
  65272. PostProcessManager.prototype.dispose = function () {
  65273. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65274. if (buffer) {
  65275. buffer.dispose();
  65276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65277. }
  65278. if (this._indexBuffer) {
  65279. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65280. this._indexBuffer = null;
  65281. }
  65282. };
  65283. return PostProcessManager;
  65284. }());
  65285. BABYLON.PostProcessManager = PostProcessManager;
  65286. })(BABYLON || (BABYLON = {}));
  65287. //# sourceMappingURL=babylon.postProcessManager.js.map
  65288. var BABYLON;
  65289. (function (BABYLON) {
  65290. /**
  65291. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65292. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65293. */
  65294. var PostProcess = /** @class */ (function () {
  65295. /**
  65296. * Creates a new instance PostProcess
  65297. * @param name The name of the PostProcess.
  65298. * @param fragmentUrl The url of the fragment shader to be used.
  65299. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65300. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65301. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65302. * @param camera The camera to apply the render pass to.
  65303. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65304. * @param engine The engine which the post process will be applied. (default: current engine)
  65305. * @param reusable If the post process can be reused on the same frame. (default: false)
  65306. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65307. * @param textureType Type of textures used when performing the post process. (default: 0)
  65308. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65309. * @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
  65310. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65311. */
  65312. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65314. if (defines === void 0) { defines = null; }
  65315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65316. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65317. if (blockCompilation === void 0) { blockCompilation = false; }
  65318. this.name = name;
  65319. /**
  65320. * Width of the texture to apply the post process on
  65321. */
  65322. this.width = -1;
  65323. /**
  65324. * Height of the texture to apply the post process on
  65325. */
  65326. this.height = -1;
  65327. /**
  65328. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65329. */
  65330. this._outputTexture = null;
  65331. /**
  65332. * If the buffer needs to be cleared before applying the post process. (default: true)
  65333. * Should be set to false if shader will overwrite all previous pixels.
  65334. */
  65335. this.autoClear = true;
  65336. /**
  65337. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65338. */
  65339. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65340. /**
  65341. * Animations to be used for the post processing
  65342. */
  65343. this.animations = new Array();
  65344. /**
  65345. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65346. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65347. */
  65348. this.enablePixelPerfectMode = false;
  65349. /**
  65350. * Force the postprocess to be applied without taking in account viewport
  65351. */
  65352. this.forceFullscreenViewport = true;
  65353. /**
  65354. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65355. *
  65356. * | Value | Type | Description |
  65357. * | ----- | ----------------------------------- | ----------- |
  65358. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65359. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65360. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65361. *
  65362. */
  65363. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65364. /**
  65365. * Force textures to be a power of two (default: false)
  65366. */
  65367. this.alwaysForcePOT = false;
  65368. /**
  65369. * Number of sample textures (default: 1)
  65370. */
  65371. this.samples = 1;
  65372. /**
  65373. * Modify the scale of the post process to be the same as the viewport (default: false)
  65374. */
  65375. this.adaptScaleToCurrentViewport = false;
  65376. this._reusable = false;
  65377. /**
  65378. * Smart array of input and output textures for the post process.
  65379. */
  65380. this._textures = new BABYLON.SmartArray(2);
  65381. /**
  65382. * The index in _textures that corresponds to the output texture.
  65383. */
  65384. this._currentRenderTextureInd = 0;
  65385. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65386. this._texelSize = BABYLON.Vector2.Zero();
  65387. // Events
  65388. /**
  65389. * An event triggered when the postprocess is activated.
  65390. */
  65391. this.onActivateObservable = new BABYLON.Observable();
  65392. /**
  65393. * An event triggered when the postprocess changes its size.
  65394. */
  65395. this.onSizeChangedObservable = new BABYLON.Observable();
  65396. /**
  65397. * An event triggered when the postprocess applies its effect.
  65398. */
  65399. this.onApplyObservable = new BABYLON.Observable();
  65400. /**
  65401. * An event triggered before rendering the postprocess
  65402. */
  65403. this.onBeforeRenderObservable = new BABYLON.Observable();
  65404. /**
  65405. * An event triggered after rendering the postprocess
  65406. */
  65407. this.onAfterRenderObservable = new BABYLON.Observable();
  65408. if (camera != null) {
  65409. this._camera = camera;
  65410. this._scene = camera.getScene();
  65411. camera.attachPostProcess(this);
  65412. this._engine = this._scene.getEngine();
  65413. this._scene.postProcesses.push(this);
  65414. }
  65415. else if (engine) {
  65416. this._engine = engine;
  65417. this._engine.postProcesses.push(this);
  65418. }
  65419. this._options = options;
  65420. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65421. this._reusable = reusable || false;
  65422. this._textureType = textureType;
  65423. this._samplers = samplers || [];
  65424. this._samplers.push("textureSampler");
  65425. this._fragmentUrl = fragmentUrl;
  65426. this._vertexUrl = vertexUrl;
  65427. this._parameters = parameters || [];
  65428. this._parameters.push("scale");
  65429. this._indexParameters = indexParameters;
  65430. if (!blockCompilation) {
  65431. this.updateEffect(defines);
  65432. }
  65433. }
  65434. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65435. /**
  65436. * A function that is added to the onActivateObservable
  65437. */
  65438. set: function (callback) {
  65439. if (this._onActivateObserver) {
  65440. this.onActivateObservable.remove(this._onActivateObserver);
  65441. }
  65442. if (callback) {
  65443. this._onActivateObserver = this.onActivateObservable.add(callback);
  65444. }
  65445. },
  65446. enumerable: true,
  65447. configurable: true
  65448. });
  65449. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65450. /**
  65451. * A function that is added to the onSizeChangedObservable
  65452. */
  65453. set: function (callback) {
  65454. if (this._onSizeChangedObserver) {
  65455. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65456. }
  65457. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65458. },
  65459. enumerable: true,
  65460. configurable: true
  65461. });
  65462. Object.defineProperty(PostProcess.prototype, "onApply", {
  65463. /**
  65464. * A function that is added to the onApplyObservable
  65465. */
  65466. set: function (callback) {
  65467. if (this._onApplyObserver) {
  65468. this.onApplyObservable.remove(this._onApplyObserver);
  65469. }
  65470. this._onApplyObserver = this.onApplyObservable.add(callback);
  65471. },
  65472. enumerable: true,
  65473. configurable: true
  65474. });
  65475. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65476. /**
  65477. * A function that is added to the onBeforeRenderObservable
  65478. */
  65479. set: function (callback) {
  65480. if (this._onBeforeRenderObserver) {
  65481. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65482. }
  65483. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65489. /**
  65490. * A function that is added to the onAfterRenderObservable
  65491. */
  65492. set: function (callback) {
  65493. if (this._onAfterRenderObserver) {
  65494. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65495. }
  65496. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65497. },
  65498. enumerable: true,
  65499. configurable: true
  65500. });
  65501. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65502. /**
  65503. * 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
  65504. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65505. */
  65506. get: function () {
  65507. return this._textures.data[this._currentRenderTextureInd];
  65508. },
  65509. set: function (value) {
  65510. this._forcedOutputTexture = value;
  65511. },
  65512. enumerable: true,
  65513. configurable: true
  65514. });
  65515. /**
  65516. * Gets the camera which post process is applied to.
  65517. * @returns The camera the post process is applied to.
  65518. */
  65519. PostProcess.prototype.getCamera = function () {
  65520. return this._camera;
  65521. };
  65522. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65523. /**
  65524. * Gets the texel size of the postprocess.
  65525. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65526. */
  65527. get: function () {
  65528. if (this._shareOutputWithPostProcess) {
  65529. return this._shareOutputWithPostProcess.texelSize;
  65530. }
  65531. if (this._forcedOutputTexture) {
  65532. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65533. }
  65534. return this._texelSize;
  65535. },
  65536. enumerable: true,
  65537. configurable: true
  65538. });
  65539. /**
  65540. * Gets the engine which this post process belongs to.
  65541. * @returns The engine the post process was enabled with.
  65542. */
  65543. PostProcess.prototype.getEngine = function () {
  65544. return this._engine;
  65545. };
  65546. /**
  65547. * The effect that is created when initializing the post process.
  65548. * @returns The created effect corrisponding the the postprocess.
  65549. */
  65550. PostProcess.prototype.getEffect = function () {
  65551. return this._effect;
  65552. };
  65553. /**
  65554. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65555. * @param postProcess The post process to share the output with.
  65556. * @returns This post process.
  65557. */
  65558. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65559. this._disposeTextures();
  65560. this._shareOutputWithPostProcess = postProcess;
  65561. return this;
  65562. };
  65563. /**
  65564. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65565. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65566. */
  65567. PostProcess.prototype.useOwnOutput = function () {
  65568. if (this._textures.length == 0) {
  65569. this._textures = new BABYLON.SmartArray(2);
  65570. }
  65571. this._shareOutputWithPostProcess = null;
  65572. };
  65573. /**
  65574. * Updates the effect with the current post process compile time values and recompiles the shader.
  65575. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65576. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65577. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65578. * @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
  65579. * @param onCompiled Called when the shader has been compiled.
  65580. * @param onError Called if there is an error when compiling a shader.
  65581. */
  65582. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65583. if (defines === void 0) { defines = null; }
  65584. if (uniforms === void 0) { uniforms = null; }
  65585. if (samplers === void 0) { samplers = null; }
  65586. 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);
  65587. };
  65588. /**
  65589. * The post process is reusable if it can be used multiple times within one frame.
  65590. * @returns If the post process is reusable
  65591. */
  65592. PostProcess.prototype.isReusable = function () {
  65593. return this._reusable;
  65594. };
  65595. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65596. PostProcess.prototype.markTextureDirty = function () {
  65597. this.width = -1;
  65598. };
  65599. /**
  65600. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65601. * 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.
  65602. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65603. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65604. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65605. * @returns The target texture that was bound to be written to.
  65606. */
  65607. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65608. var _this = this;
  65609. if (sourceTexture === void 0) { sourceTexture = null; }
  65610. camera = camera || this._camera;
  65611. var scene = camera.getScene();
  65612. var engine = scene.getEngine();
  65613. var maxSize = engine.getCaps().maxTextureSize;
  65614. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65615. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65616. // 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
  65617. var webVRCamera = camera.parent;
  65618. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65619. requiredWidth /= 2;
  65620. }
  65621. var desiredWidth = (this._options.width || requiredWidth);
  65622. var desiredHeight = this._options.height || requiredHeight;
  65623. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65624. if (this.adaptScaleToCurrentViewport) {
  65625. var currentViewport = engine.currentViewport;
  65626. if (currentViewport) {
  65627. desiredWidth *= currentViewport.width;
  65628. desiredHeight *= currentViewport.height;
  65629. }
  65630. }
  65631. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65632. if (!this._options.width) {
  65633. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65634. }
  65635. if (!this._options.height) {
  65636. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65637. }
  65638. }
  65639. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65640. if (this._textures.length > 0) {
  65641. for (var i = 0; i < this._textures.length; i++) {
  65642. this._engine._releaseTexture(this._textures.data[i]);
  65643. }
  65644. this._textures.reset();
  65645. }
  65646. this.width = desiredWidth;
  65647. this.height = desiredHeight;
  65648. var textureSize = { width: this.width, height: this.height };
  65649. var textureOptions = {
  65650. generateMipMaps: false,
  65651. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65652. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65653. samplingMode: this.renderTargetSamplingMode,
  65654. type: this._textureType
  65655. };
  65656. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65657. if (this._reusable) {
  65658. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65659. }
  65660. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65661. this.onSizeChangedObservable.notifyObservers(this);
  65662. }
  65663. this._textures.forEach(function (texture) {
  65664. if (texture.samples !== _this.samples) {
  65665. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65666. }
  65667. });
  65668. }
  65669. var target;
  65670. if (this._shareOutputWithPostProcess) {
  65671. target = this._shareOutputWithPostProcess.inputTexture;
  65672. }
  65673. else if (this._forcedOutputTexture) {
  65674. target = this._forcedOutputTexture;
  65675. this.width = this._forcedOutputTexture.width;
  65676. this.height = this._forcedOutputTexture.height;
  65677. }
  65678. else {
  65679. target = this.inputTexture;
  65680. }
  65681. // Bind the input of this post process to be used as the output of the previous post process.
  65682. if (this.enablePixelPerfectMode) {
  65683. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65684. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65685. }
  65686. else {
  65687. this._scaleRatio.copyFromFloats(1, 1);
  65688. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65689. }
  65690. this.onActivateObservable.notifyObservers(camera);
  65691. // Clear
  65692. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65693. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65694. }
  65695. if (this._reusable) {
  65696. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65697. }
  65698. return target;
  65699. };
  65700. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65701. /**
  65702. * If the post process is supported.
  65703. */
  65704. get: function () {
  65705. return this._effect.isSupported;
  65706. },
  65707. enumerable: true,
  65708. configurable: true
  65709. });
  65710. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65711. /**
  65712. * The aspect ratio of the output texture.
  65713. */
  65714. get: function () {
  65715. if (this._shareOutputWithPostProcess) {
  65716. return this._shareOutputWithPostProcess.aspectRatio;
  65717. }
  65718. if (this._forcedOutputTexture) {
  65719. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65720. }
  65721. return this.width / this.height;
  65722. },
  65723. enumerable: true,
  65724. configurable: true
  65725. });
  65726. /**
  65727. * Get a value indicating if the post-process is ready to be used
  65728. * @returns true if the post-process is ready (shader is compiled)
  65729. */
  65730. PostProcess.prototype.isReady = function () {
  65731. return this._effect && this._effect.isReady();
  65732. };
  65733. /**
  65734. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65735. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65736. */
  65737. PostProcess.prototype.apply = function () {
  65738. // Check
  65739. if (!this._effect || !this._effect.isReady())
  65740. return null;
  65741. // States
  65742. this._engine.enableEffect(this._effect);
  65743. this._engine.setState(false);
  65744. this._engine.setDepthBuffer(false);
  65745. this._engine.setDepthWrite(false);
  65746. // Alpha
  65747. this._engine.setAlphaMode(this.alphaMode);
  65748. if (this.alphaConstants) {
  65749. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65750. }
  65751. // Bind the output texture of the preivous post process as the input to this post process.
  65752. var source;
  65753. if (this._shareOutputWithPostProcess) {
  65754. source = this._shareOutputWithPostProcess.inputTexture;
  65755. }
  65756. else if (this._forcedOutputTexture) {
  65757. source = this._forcedOutputTexture;
  65758. }
  65759. else {
  65760. source = this.inputTexture;
  65761. }
  65762. this._effect._bindTexture("textureSampler", source);
  65763. // Parameters
  65764. this._effect.setVector2("scale", this._scaleRatio);
  65765. this.onApplyObservable.notifyObservers(this._effect);
  65766. return this._effect;
  65767. };
  65768. PostProcess.prototype._disposeTextures = function () {
  65769. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65770. return;
  65771. }
  65772. if (this._textures.length > 0) {
  65773. for (var i = 0; i < this._textures.length; i++) {
  65774. this._engine._releaseTexture(this._textures.data[i]);
  65775. }
  65776. }
  65777. this._textures.dispose();
  65778. };
  65779. /**
  65780. * Disposes the post process.
  65781. * @param camera The camera to dispose the post process on.
  65782. */
  65783. PostProcess.prototype.dispose = function (camera) {
  65784. camera = camera || this._camera;
  65785. this._disposeTextures();
  65786. if (this._scene) {
  65787. var index_1 = this._scene.postProcesses.indexOf(this);
  65788. if (index_1 !== -1) {
  65789. this._scene.postProcesses.splice(index_1, 1);
  65790. }
  65791. }
  65792. else {
  65793. var index_2 = this._engine.postProcesses.indexOf(this);
  65794. if (index_2 !== -1) {
  65795. this._engine.postProcesses.splice(index_2, 1);
  65796. }
  65797. }
  65798. if (!camera) {
  65799. return;
  65800. }
  65801. camera.detachPostProcess(this);
  65802. var index = camera._postProcesses.indexOf(this);
  65803. if (index === 0 && camera._postProcesses.length > 0) {
  65804. var firstPostProcess = this._camera._getFirstPostProcess();
  65805. if (firstPostProcess) {
  65806. firstPostProcess.markTextureDirty();
  65807. }
  65808. }
  65809. this.onActivateObservable.clear();
  65810. this.onAfterRenderObservable.clear();
  65811. this.onApplyObservable.clear();
  65812. this.onBeforeRenderObservable.clear();
  65813. this.onSizeChangedObservable.clear();
  65814. };
  65815. return PostProcess;
  65816. }());
  65817. BABYLON.PostProcess = PostProcess;
  65818. })(BABYLON || (BABYLON = {}));
  65819. //# sourceMappingURL=babylon.postProcess.js.map
  65820. var BABYLON;
  65821. (function (BABYLON) {
  65822. var PassPostProcess = /** @class */ (function (_super) {
  65823. __extends(PassPostProcess, _super);
  65824. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65825. if (camera === void 0) { camera = null; }
  65826. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65827. if (blockCompilation === void 0) { blockCompilation = false; }
  65828. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65829. }
  65830. return PassPostProcess;
  65831. }(BABYLON.PostProcess));
  65832. BABYLON.PassPostProcess = PassPostProcess;
  65833. })(BABYLON || (BABYLON = {}));
  65834. //# sourceMappingURL=babylon.passPostProcess.js.map
  65835. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65836. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65837. s = arguments[i];
  65838. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65839. t[p] = s[p];
  65840. }
  65841. return t;
  65842. };
  65843. var BABYLON;
  65844. (function (BABYLON) {
  65845. /**
  65846. * Default implementation IShadowGenerator.
  65847. * This is the main object responsible of generating shadows in the framework.
  65848. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65849. */
  65850. var ShadowGenerator = /** @class */ (function () {
  65851. /**
  65852. * Creates a ShadowGenerator object.
  65853. * A ShadowGenerator is the required tool to use the shadows.
  65854. * Each light casting shadows needs to use its own ShadowGenerator.
  65855. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65856. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65857. * @param light The light object generating the shadows.
  65858. * @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.
  65859. */
  65860. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65861. this._bias = 0.00005;
  65862. this._normalBias = 0;
  65863. this._blurBoxOffset = 1;
  65864. this._blurScale = 2;
  65865. this._blurKernel = 1;
  65866. this._useKernelBlur = false;
  65867. this._filter = ShadowGenerator.FILTER_NONE;
  65868. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65869. this._contactHardeningLightSizeUVRatio = 0.1;
  65870. this._darkness = 0;
  65871. this._transparencyShadow = false;
  65872. /**
  65873. * Controls the extent to which the shadows fade out at the edge of the frustum
  65874. * Used only by directionals and spots
  65875. */
  65876. this.frustumEdgeFalloff = 0;
  65877. /**
  65878. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65879. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65880. * It might on the other hand introduce peter panning.
  65881. */
  65882. this.forceBackFacesOnly = false;
  65883. this._lightDirection = BABYLON.Vector3.Zero();
  65884. this._viewMatrix = BABYLON.Matrix.Zero();
  65885. this._projectionMatrix = BABYLON.Matrix.Zero();
  65886. this._transformMatrix = BABYLON.Matrix.Zero();
  65887. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65888. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65889. this._currentFaceIndex = 0;
  65890. this._currentFaceIndexCache = 0;
  65891. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65892. this._mapSize = mapSize;
  65893. this._light = light;
  65894. this._scene = light.getScene();
  65895. light._shadowGenerator = this;
  65896. // Texture type fallback from float to int if not supported.
  65897. var caps = this._scene.getEngine().getCaps();
  65898. if (!useFullFloatFirst) {
  65899. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65900. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65901. }
  65902. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65903. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65904. }
  65905. else {
  65906. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65907. }
  65908. }
  65909. else {
  65910. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65911. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65912. }
  65913. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65914. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65915. }
  65916. else {
  65917. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65918. }
  65919. }
  65920. this._initializeGenerator();
  65921. this._applyFilterValues();
  65922. }
  65923. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65924. /**
  65925. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65926. */
  65927. get: function () {
  65928. return this._bias;
  65929. },
  65930. /**
  65931. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65932. */
  65933. set: function (bias) {
  65934. this._bias = bias;
  65935. },
  65936. enumerable: true,
  65937. configurable: true
  65938. });
  65939. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65940. /**
  65941. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65942. */
  65943. get: function () {
  65944. return this._normalBias;
  65945. },
  65946. /**
  65947. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65948. */
  65949. set: function (normalBias) {
  65950. this._normalBias = normalBias;
  65951. },
  65952. enumerable: true,
  65953. configurable: true
  65954. });
  65955. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65956. /**
  65957. * Gets the blur box offset: offset applied during the blur pass.
  65958. * Only usefull if useKernelBlur = false
  65959. */
  65960. get: function () {
  65961. return this._blurBoxOffset;
  65962. },
  65963. /**
  65964. * Sets the blur box offset: offset applied during the blur pass.
  65965. * Only usefull if useKernelBlur = false
  65966. */
  65967. set: function (value) {
  65968. if (this._blurBoxOffset === value) {
  65969. return;
  65970. }
  65971. this._blurBoxOffset = value;
  65972. this._disposeBlurPostProcesses();
  65973. },
  65974. enumerable: true,
  65975. configurable: true
  65976. });
  65977. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65978. /**
  65979. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65980. * 2 means half of the size.
  65981. */
  65982. get: function () {
  65983. return this._blurScale;
  65984. },
  65985. /**
  65986. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65987. * 2 means half of the size.
  65988. */
  65989. set: function (value) {
  65990. if (this._blurScale === value) {
  65991. return;
  65992. }
  65993. this._blurScale = value;
  65994. this._disposeBlurPostProcesses();
  65995. },
  65996. enumerable: true,
  65997. configurable: true
  65998. });
  65999. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66000. /**
  66001. * Gets the blur kernel: kernel size of the blur pass.
  66002. * Only usefull if useKernelBlur = true
  66003. */
  66004. get: function () {
  66005. return this._blurKernel;
  66006. },
  66007. /**
  66008. * Sets the blur kernel: kernel size of the blur pass.
  66009. * Only usefull if useKernelBlur = true
  66010. */
  66011. set: function (value) {
  66012. if (this._blurKernel === value) {
  66013. return;
  66014. }
  66015. this._blurKernel = value;
  66016. this._disposeBlurPostProcesses();
  66017. },
  66018. enumerable: true,
  66019. configurable: true
  66020. });
  66021. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66022. /**
  66023. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66024. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66025. */
  66026. get: function () {
  66027. return this._useKernelBlur;
  66028. },
  66029. /**
  66030. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66031. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66032. */
  66033. set: function (value) {
  66034. if (this._useKernelBlur === value) {
  66035. return;
  66036. }
  66037. this._useKernelBlur = value;
  66038. this._disposeBlurPostProcesses();
  66039. },
  66040. enumerable: true,
  66041. configurable: true
  66042. });
  66043. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66044. /**
  66045. * Gets the depth scale used in ESM mode.
  66046. */
  66047. get: function () {
  66048. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66049. },
  66050. /**
  66051. * Sets the depth scale used in ESM mode.
  66052. * This can override the scale stored on the light.
  66053. */
  66054. set: function (value) {
  66055. this._depthScale = value;
  66056. },
  66057. enumerable: true,
  66058. configurable: true
  66059. });
  66060. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66061. /**
  66062. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66063. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66064. */
  66065. get: function () {
  66066. return this._filter;
  66067. },
  66068. /**
  66069. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66070. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66071. */
  66072. set: function (value) {
  66073. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66074. if (this._light.needCube()) {
  66075. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66076. this.useExponentialShadowMap = true;
  66077. return;
  66078. }
  66079. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66080. this.useCloseExponentialShadowMap = true;
  66081. return;
  66082. }
  66083. // PCF on cubemap would also be expensive
  66084. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66085. this.usePoissonSampling = true;
  66086. return;
  66087. }
  66088. }
  66089. // Weblg1 fallback for PCF.
  66090. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66091. if (this._scene.getEngine().webGLVersion === 1) {
  66092. this.usePoissonSampling = true;
  66093. return;
  66094. }
  66095. }
  66096. if (this._filter === value) {
  66097. return;
  66098. }
  66099. this._filter = value;
  66100. this._disposeBlurPostProcesses();
  66101. this._applyFilterValues();
  66102. this._light._markMeshesAsLightDirty();
  66103. },
  66104. enumerable: true,
  66105. configurable: true
  66106. });
  66107. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66108. /**
  66109. * Gets if the current filter is set to Poisson Sampling.
  66110. */
  66111. get: function () {
  66112. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66113. },
  66114. /**
  66115. * Sets the current filter to Poisson Sampling.
  66116. */
  66117. set: function (value) {
  66118. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66119. return;
  66120. }
  66121. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66122. },
  66123. enumerable: true,
  66124. configurable: true
  66125. });
  66126. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66127. /**
  66128. * Gets if the current filter is set to VSM.
  66129. * DEPRECATED. Should use useExponentialShadowMap instead.
  66130. */
  66131. get: function () {
  66132. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66133. return this.useExponentialShadowMap;
  66134. },
  66135. /**
  66136. * Sets the current filter is to VSM.
  66137. * DEPRECATED. Should use useExponentialShadowMap instead.
  66138. */
  66139. set: function (value) {
  66140. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66141. this.useExponentialShadowMap = value;
  66142. },
  66143. enumerable: true,
  66144. configurable: true
  66145. });
  66146. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66147. /**
  66148. * Gets if the current filter is set to blurred VSM.
  66149. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66150. */
  66151. get: function () {
  66152. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66153. return this.useBlurExponentialShadowMap;
  66154. },
  66155. /**
  66156. * Sets the current filter is to blurred VSM.
  66157. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66158. */
  66159. set: function (value) {
  66160. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66161. this.useBlurExponentialShadowMap = value;
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66167. /**
  66168. * Gets if the current filter is set to ESM.
  66169. */
  66170. get: function () {
  66171. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66172. },
  66173. /**
  66174. * Sets the current filter is to ESM.
  66175. */
  66176. set: function (value) {
  66177. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66178. return;
  66179. }
  66180. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66181. },
  66182. enumerable: true,
  66183. configurable: true
  66184. });
  66185. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66186. /**
  66187. * Gets if the current filter is set to filtered ESM.
  66188. */
  66189. get: function () {
  66190. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66191. },
  66192. /**
  66193. * Gets if the current filter is set to filtered ESM.
  66194. */
  66195. set: function (value) {
  66196. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66197. return;
  66198. }
  66199. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66200. },
  66201. enumerable: true,
  66202. configurable: true
  66203. });
  66204. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66205. /**
  66206. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66207. * exponential to prevent steep falloff artifacts).
  66208. */
  66209. get: function () {
  66210. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66211. },
  66212. /**
  66213. * Sets the current filter to "close ESM" (using the inverse of the
  66214. * exponential to prevent steep falloff artifacts).
  66215. */
  66216. set: function (value) {
  66217. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66218. return;
  66219. }
  66220. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66221. },
  66222. enumerable: true,
  66223. configurable: true
  66224. });
  66225. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66226. /**
  66227. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66228. * exponential to prevent steep falloff artifacts).
  66229. */
  66230. get: function () {
  66231. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66232. },
  66233. /**
  66234. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66235. * exponential to prevent steep falloff artifacts).
  66236. */
  66237. set: function (value) {
  66238. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66239. return;
  66240. }
  66241. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66247. /**
  66248. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66249. */
  66250. get: function () {
  66251. return this.filter === ShadowGenerator.FILTER_PCF;
  66252. },
  66253. /**
  66254. * Sets the current filter to "PCF" (percentage closer filtering).
  66255. */
  66256. set: function (value) {
  66257. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66258. return;
  66259. }
  66260. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66261. },
  66262. enumerable: true,
  66263. configurable: true
  66264. });
  66265. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66266. /**
  66267. * Gets the PCF or PCSS Quality.
  66268. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66269. */
  66270. get: function () {
  66271. return this._filteringQuality;
  66272. },
  66273. /**
  66274. * Sets the PCF or PCSS Quality.
  66275. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66276. */
  66277. set: function (filteringQuality) {
  66278. this._filteringQuality = filteringQuality;
  66279. },
  66280. enumerable: true,
  66281. configurable: true
  66282. });
  66283. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66284. /**
  66285. * Gets if the current filter is set to "PCSS" (contact hardening).
  66286. */
  66287. get: function () {
  66288. return this.filter === ShadowGenerator.FILTER_PCSS;
  66289. },
  66290. /**
  66291. * Sets the current filter to "PCSS" (contact hardening).
  66292. */
  66293. set: function (value) {
  66294. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66295. return;
  66296. }
  66297. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66303. /**
  66304. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66305. * Using a ratio helps keeping shape stability independently of the map size.
  66306. *
  66307. * It does not account for the light projection as it was having too much
  66308. * instability during the light setup or during light position changes.
  66309. *
  66310. * Only valid if useContactHardeningShadow is true.
  66311. */
  66312. get: function () {
  66313. return this._contactHardeningLightSizeUVRatio;
  66314. },
  66315. /**
  66316. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66317. * Using a ratio helps keeping shape stability independently of the map size.
  66318. *
  66319. * It does not account for the light projection as it was having too much
  66320. * instability during the light setup or during light position changes.
  66321. *
  66322. * Only valid if useContactHardeningShadow is true.
  66323. */
  66324. set: function (contactHardeningLightSizeUVRatio) {
  66325. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66326. },
  66327. enumerable: true,
  66328. configurable: true
  66329. });
  66330. /**
  66331. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66332. * 0 means strongest and 1 would means no shadow.
  66333. * @returns the darkness.
  66334. */
  66335. ShadowGenerator.prototype.getDarkness = function () {
  66336. return this._darkness;
  66337. };
  66338. /**
  66339. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66340. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66341. * @returns the shadow generator allowing fluent coding.
  66342. */
  66343. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66344. if (darkness >= 1.0)
  66345. this._darkness = 1.0;
  66346. else if (darkness <= 0.0)
  66347. this._darkness = 0.0;
  66348. else
  66349. this._darkness = darkness;
  66350. return this;
  66351. };
  66352. /**
  66353. * Sets the ability to have transparent shadow (boolean).
  66354. * @param transparent True if transparent else False
  66355. * @returns the shadow generator allowing fluent coding
  66356. */
  66357. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66358. this._transparencyShadow = transparent;
  66359. return this;
  66360. };
  66361. /**
  66362. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66363. * @returns The render target texture if present otherwise, null
  66364. */
  66365. ShadowGenerator.prototype.getShadowMap = function () {
  66366. return this._shadowMap;
  66367. };
  66368. /**
  66369. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66370. * @returns The render target texture if the shadow map is present otherwise, null
  66371. */
  66372. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66373. if (this._shadowMap2) {
  66374. return this._shadowMap2;
  66375. }
  66376. return this._shadowMap;
  66377. };
  66378. /**
  66379. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66380. * @param mesh Mesh to add
  66381. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66382. * @returns the Shadow Generator itself
  66383. */
  66384. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66385. if (includeDescendants === void 0) { includeDescendants = true; }
  66386. if (!this._shadowMap) {
  66387. return this;
  66388. }
  66389. if (!this._shadowMap.renderList) {
  66390. this._shadowMap.renderList = [];
  66391. }
  66392. this._shadowMap.renderList.push(mesh);
  66393. if (includeDescendants) {
  66394. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66395. }
  66396. return this;
  66397. var _a;
  66398. };
  66399. /**
  66400. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66401. * @param mesh Mesh to remove
  66402. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66403. * @returns the Shadow Generator itself
  66404. */
  66405. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66406. if (includeDescendants === void 0) { includeDescendants = true; }
  66407. if (!this._shadowMap || !this._shadowMap.renderList) {
  66408. return this;
  66409. }
  66410. var index = this._shadowMap.renderList.indexOf(mesh);
  66411. if (index !== -1) {
  66412. this._shadowMap.renderList.splice(index, 1);
  66413. }
  66414. if (includeDescendants) {
  66415. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66416. var child = _a[_i];
  66417. this.removeShadowCaster(child);
  66418. }
  66419. }
  66420. return this;
  66421. };
  66422. /**
  66423. * Returns the associated light object.
  66424. * @returns the light generating the shadow
  66425. */
  66426. ShadowGenerator.prototype.getLight = function () {
  66427. return this._light;
  66428. };
  66429. ShadowGenerator.prototype._initializeGenerator = function () {
  66430. this._light._markMeshesAsLightDirty();
  66431. this._initializeShadowMap();
  66432. };
  66433. ShadowGenerator.prototype._initializeShadowMap = function () {
  66434. var _this = this;
  66435. // Render target
  66436. var engine = this._scene.getEngine();
  66437. if (engine.webGLVersion > 1) {
  66438. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66439. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66440. }
  66441. else {
  66442. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66443. }
  66444. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66445. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66446. this._shadowMap.anisotropicFilteringLevel = 1;
  66447. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66448. this._shadowMap.renderParticles = false;
  66449. this._shadowMap.ignoreCameraViewport = true;
  66450. // Record Face Index before render.
  66451. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66452. _this._currentFaceIndex = faceIndex;
  66453. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66454. engine.setColorWrite(false);
  66455. }
  66456. });
  66457. // Custom render function.
  66458. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66459. // Blur if required afer render.
  66460. this._shadowMap.onAfterUnbindObservable.add(function () {
  66461. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66462. engine.setColorWrite(true);
  66463. }
  66464. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66465. return;
  66466. }
  66467. var shadowMap = _this.getShadowMapForRendering();
  66468. if (shadowMap) {
  66469. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66470. }
  66471. });
  66472. // Clear according to the chosen filter.
  66473. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66474. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66475. this._shadowMap.onClearObservable.add(function (engine) {
  66476. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66477. engine.clear(clearOne, false, true, false);
  66478. }
  66479. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66480. engine.clear(clearZero, true, true, false);
  66481. }
  66482. else {
  66483. engine.clear(clearOne, true, true, false);
  66484. }
  66485. });
  66486. };
  66487. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66488. var _this = this;
  66489. var engine = this._scene.getEngine();
  66490. var targetSize = this._mapSize / this.blurScale;
  66491. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66492. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66493. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66494. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66495. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66496. }
  66497. if (this.useKernelBlur) {
  66498. 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);
  66499. this._kernelBlurXPostprocess.width = targetSize;
  66500. this._kernelBlurXPostprocess.height = targetSize;
  66501. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66502. effect.setTexture("textureSampler", _this._shadowMap);
  66503. });
  66504. 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);
  66505. this._kernelBlurXPostprocess.autoClear = false;
  66506. this._kernelBlurYPostprocess.autoClear = false;
  66507. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66508. this._kernelBlurXPostprocess.packedFloat = true;
  66509. this._kernelBlurYPostprocess.packedFloat = true;
  66510. }
  66511. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66512. }
  66513. else {
  66514. 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);
  66515. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66516. effect.setFloat2("screenSize", targetSize, targetSize);
  66517. effect.setTexture("textureSampler", _this._shadowMap);
  66518. });
  66519. this._boxBlurPostprocess.autoClear = false;
  66520. this._blurPostProcesses = [this._boxBlurPostprocess];
  66521. }
  66522. };
  66523. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66524. var index;
  66525. var engine = this._scene.getEngine();
  66526. if (depthOnlySubMeshes.length) {
  66527. engine.setColorWrite(false);
  66528. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66529. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66530. }
  66531. engine.setColorWrite(true);
  66532. }
  66533. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66534. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66535. }
  66536. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66537. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66538. }
  66539. if (this._transparencyShadow) {
  66540. for (index = 0; index < transparentSubMeshes.length; index++) {
  66541. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66542. }
  66543. }
  66544. };
  66545. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66546. var _this = this;
  66547. var mesh = subMesh.getRenderingMesh();
  66548. var scene = this._scene;
  66549. var engine = scene.getEngine();
  66550. var material = subMesh.getMaterial();
  66551. if (!material) {
  66552. return;
  66553. }
  66554. // Culling
  66555. engine.setState(material.backFaceCulling);
  66556. // Managing instances
  66557. var batch = mesh._getInstancesRenderList(subMesh._id);
  66558. if (batch.mustReturn) {
  66559. return;
  66560. }
  66561. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66562. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66563. engine.enableEffect(this._effect);
  66564. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66565. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66566. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66567. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66568. this._effect.setVector3("lightData", this._cachedDirection);
  66569. }
  66570. else {
  66571. this._effect.setVector3("lightData", this._cachedPosition);
  66572. }
  66573. if (scene.activeCamera) {
  66574. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66575. }
  66576. // Alpha test
  66577. if (material && material.needAlphaTesting()) {
  66578. var alphaTexture = material.getAlphaTestTexture();
  66579. if (alphaTexture) {
  66580. this._effect.setTexture("diffuseSampler", alphaTexture);
  66581. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66582. }
  66583. }
  66584. // Bones
  66585. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66586. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66587. }
  66588. // Morph targets
  66589. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66590. if (this.forceBackFacesOnly) {
  66591. engine.setState(true, 0, false, true);
  66592. }
  66593. // Draw
  66594. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66595. if (this.forceBackFacesOnly) {
  66596. engine.setState(true, 0, false, false);
  66597. }
  66598. }
  66599. else {
  66600. // Need to reset refresh rate of the shadowMap
  66601. if (this._shadowMap) {
  66602. this._shadowMap.resetRefreshCounter();
  66603. }
  66604. }
  66605. };
  66606. ShadowGenerator.prototype._applyFilterValues = function () {
  66607. if (!this._shadowMap) {
  66608. return;
  66609. }
  66610. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66611. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66612. }
  66613. else {
  66614. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66615. }
  66616. };
  66617. /**
  66618. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66619. * @param onCompiled Callback triggered at the and of the effects compilation
  66620. * @param options Sets of optional options forcing the compilation with different modes
  66621. */
  66622. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66623. var _this = this;
  66624. var localOptions = __assign({ useInstances: false }, options);
  66625. var shadowMap = this.getShadowMap();
  66626. if (!shadowMap) {
  66627. if (onCompiled) {
  66628. onCompiled(this);
  66629. }
  66630. return;
  66631. }
  66632. var renderList = shadowMap.renderList;
  66633. if (!renderList) {
  66634. if (onCompiled) {
  66635. onCompiled(this);
  66636. }
  66637. return;
  66638. }
  66639. var subMeshes = new Array();
  66640. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66641. var mesh = renderList_1[_i];
  66642. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66643. }
  66644. if (subMeshes.length === 0) {
  66645. if (onCompiled) {
  66646. onCompiled(this);
  66647. }
  66648. return;
  66649. }
  66650. var currentIndex = 0;
  66651. var checkReady = function () {
  66652. if (!_this._scene || !_this._scene.getEngine()) {
  66653. return;
  66654. }
  66655. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66656. currentIndex++;
  66657. if (currentIndex >= subMeshes.length) {
  66658. if (onCompiled) {
  66659. onCompiled(_this);
  66660. }
  66661. return;
  66662. }
  66663. }
  66664. setTimeout(checkReady, 16);
  66665. };
  66666. checkReady();
  66667. };
  66668. /**
  66669. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66670. * @param options Sets of optional options forcing the compilation with different modes
  66671. * @returns A promise that resolves when the compilation completes
  66672. */
  66673. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66674. var _this = this;
  66675. return new Promise(function (resolve) {
  66676. _this.forceCompilation(function () {
  66677. resolve();
  66678. }, options);
  66679. });
  66680. };
  66681. /**
  66682. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66683. * @param subMesh The submesh we want to render in the shadow map
  66684. * @param useInstances Defines wether will draw in the map using instances
  66685. * @returns true if ready otherwise, false
  66686. */
  66687. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66688. var defines = [];
  66689. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66690. defines.push("#define FLOAT");
  66691. }
  66692. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66693. defines.push("#define ESM");
  66694. }
  66695. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66696. defines.push("#define DEPTHTEXTURE");
  66697. }
  66698. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66699. var mesh = subMesh.getMesh();
  66700. var material = subMesh.getMaterial();
  66701. // Normal bias.
  66702. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66703. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66704. defines.push("#define NORMAL");
  66705. if (mesh.nonUniformScaling) {
  66706. defines.push("#define NONUNIFORMSCALING");
  66707. }
  66708. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66709. defines.push("#define DIRECTIONINLIGHTDATA");
  66710. }
  66711. }
  66712. // Alpha test
  66713. if (material && material.needAlphaTesting()) {
  66714. var alphaTexture = material.getAlphaTestTexture();
  66715. if (alphaTexture) {
  66716. defines.push("#define ALPHATEST");
  66717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66718. attribs.push(BABYLON.VertexBuffer.UVKind);
  66719. defines.push("#define UV1");
  66720. }
  66721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66722. if (alphaTexture.coordinatesIndex === 1) {
  66723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66724. defines.push("#define UV2");
  66725. }
  66726. }
  66727. }
  66728. }
  66729. // Bones
  66730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66733. if (mesh.numBoneInfluencers > 4) {
  66734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66736. }
  66737. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66738. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66739. }
  66740. else {
  66741. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66742. }
  66743. // Morph targets
  66744. var manager = mesh.morphTargetManager;
  66745. var morphInfluencers = 0;
  66746. if (manager) {
  66747. if (manager.numInfluencers > 0) {
  66748. defines.push("#define MORPHTARGETS");
  66749. morphInfluencers = manager.numInfluencers;
  66750. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66751. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66752. }
  66753. }
  66754. // Instances
  66755. if (useInstances) {
  66756. defines.push("#define INSTANCES");
  66757. attribs.push("world0");
  66758. attribs.push("world1");
  66759. attribs.push("world2");
  66760. attribs.push("world3");
  66761. }
  66762. // Get correct effect
  66763. var join = defines.join("\n");
  66764. if (this._cachedDefines !== join) {
  66765. this._cachedDefines = join;
  66766. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66767. }
  66768. if (!this._effect.isReady()) {
  66769. return false;
  66770. }
  66771. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66772. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66773. this._initializeBlurRTTAndPostProcesses();
  66774. }
  66775. }
  66776. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66777. return false;
  66778. }
  66779. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66780. return false;
  66781. }
  66782. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66783. return false;
  66784. }
  66785. return true;
  66786. };
  66787. /**
  66788. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66789. * @param defines Defines of the material we want to update
  66790. * @param lightIndex Index of the light in the enabled light list of the material
  66791. */
  66792. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66793. var scene = this._scene;
  66794. var light = this._light;
  66795. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66796. return;
  66797. }
  66798. defines["SHADOW" + lightIndex] = true;
  66799. if (this.useContactHardeningShadow) {
  66800. defines["SHADOWPCSS" + lightIndex] = true;
  66801. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66802. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66803. }
  66804. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66805. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66806. }
  66807. // else default to high.
  66808. }
  66809. if (this.usePercentageCloserFiltering) {
  66810. defines["SHADOWPCF" + lightIndex] = true;
  66811. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66812. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66813. }
  66814. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66815. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66816. }
  66817. // else default to high.
  66818. }
  66819. else if (this.usePoissonSampling) {
  66820. defines["SHADOWPOISSON" + lightIndex] = true;
  66821. }
  66822. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66823. defines["SHADOWESM" + lightIndex] = true;
  66824. }
  66825. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66826. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66827. }
  66828. if (light.needCube()) {
  66829. defines["SHADOWCUBE" + lightIndex] = true;
  66830. }
  66831. };
  66832. /**
  66833. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66834. * defined in the generator but impacting the effect).
  66835. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66836. * @param effect The effect we are binfing the information for
  66837. */
  66838. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66839. var light = this._light;
  66840. var scene = this._scene;
  66841. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66842. return;
  66843. }
  66844. var camera = scene.activeCamera;
  66845. if (!camera) {
  66846. return;
  66847. }
  66848. var shadowMap = this.getShadowMap();
  66849. if (!shadowMap) {
  66850. return;
  66851. }
  66852. if (!light.needCube()) {
  66853. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66854. }
  66855. // Only PCF uses depth stencil texture.
  66856. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66857. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66858. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66859. }
  66860. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66861. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66862. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66863. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66864. }
  66865. else {
  66866. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66867. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66868. }
  66869. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66870. };
  66871. /**
  66872. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66873. * (eq to shadow prjection matrix * light transform matrix)
  66874. * @returns The transform matrix used to create the shadow map
  66875. */
  66876. ShadowGenerator.prototype.getTransformMatrix = function () {
  66877. var scene = this._scene;
  66878. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66879. return this._transformMatrix;
  66880. }
  66881. this._currentRenderID = scene.getRenderId();
  66882. this._currentFaceIndexCache = this._currentFaceIndex;
  66883. var lightPosition = this._light.position;
  66884. if (this._light.computeTransformedInformation()) {
  66885. lightPosition = this._light.transformedPosition;
  66886. }
  66887. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66888. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66889. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66890. }
  66891. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66892. this._cachedPosition.copyFrom(lightPosition);
  66893. this._cachedDirection.copyFrom(this._lightDirection);
  66894. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66895. var shadowMap = this.getShadowMap();
  66896. if (shadowMap) {
  66897. var renderList = shadowMap.renderList;
  66898. if (renderList) {
  66899. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66900. }
  66901. }
  66902. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66903. }
  66904. return this._transformMatrix;
  66905. };
  66906. /**
  66907. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66908. * Cube and 2D textures for instance.
  66909. */
  66910. ShadowGenerator.prototype.recreateShadowMap = function () {
  66911. var shadowMap = this._shadowMap;
  66912. if (!shadowMap) {
  66913. return;
  66914. }
  66915. // Track render list.
  66916. var renderList = shadowMap.renderList;
  66917. // Clean up existing data.
  66918. this._disposeRTTandPostProcesses();
  66919. // Reinitializes.
  66920. this._initializeGenerator();
  66921. // Reaffect the filter to ensure a correct fallback if necessary.
  66922. this.filter = this.filter;
  66923. // Reaffect the filter.
  66924. this._applyFilterValues();
  66925. // Reaffect Render List.
  66926. this._shadowMap.renderList = renderList;
  66927. };
  66928. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66929. if (this._shadowMap2) {
  66930. this._shadowMap2.dispose();
  66931. this._shadowMap2 = null;
  66932. }
  66933. if (this._boxBlurPostprocess) {
  66934. this._boxBlurPostprocess.dispose();
  66935. this._boxBlurPostprocess = null;
  66936. }
  66937. if (this._kernelBlurXPostprocess) {
  66938. this._kernelBlurXPostprocess.dispose();
  66939. this._kernelBlurXPostprocess = null;
  66940. }
  66941. if (this._kernelBlurYPostprocess) {
  66942. this._kernelBlurYPostprocess.dispose();
  66943. this._kernelBlurYPostprocess = null;
  66944. }
  66945. this._blurPostProcesses = [];
  66946. };
  66947. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66948. if (this._shadowMap) {
  66949. this._shadowMap.dispose();
  66950. this._shadowMap = null;
  66951. }
  66952. this._disposeBlurPostProcesses();
  66953. };
  66954. /**
  66955. * Disposes the ShadowGenerator.
  66956. * Returns nothing.
  66957. */
  66958. ShadowGenerator.prototype.dispose = function () {
  66959. this._disposeRTTandPostProcesses();
  66960. if (this._light) {
  66961. this._light._shadowGenerator = null;
  66962. this._light._markMeshesAsLightDirty();
  66963. }
  66964. };
  66965. /**
  66966. * Serializes the shadow generator setup to a json object.
  66967. * @returns The serialized JSON object
  66968. */
  66969. ShadowGenerator.prototype.serialize = function () {
  66970. var serializationObject = {};
  66971. var shadowMap = this.getShadowMap();
  66972. if (!shadowMap) {
  66973. return serializationObject;
  66974. }
  66975. serializationObject.lightId = this._light.id;
  66976. serializationObject.mapSize = shadowMap.getRenderSize();
  66977. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66978. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66979. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66980. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66981. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66982. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66983. serializationObject.depthScale = this.depthScale;
  66984. serializationObject.darkness = this.getDarkness();
  66985. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66986. serializationObject.blurKernel = this.blurKernel;
  66987. serializationObject.blurScale = this.blurScale;
  66988. serializationObject.useKernelBlur = this.useKernelBlur;
  66989. serializationObject.transparencyShadow = this._transparencyShadow;
  66990. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66991. serializationObject.bias = this.bias;
  66992. serializationObject.normalBias = this.normalBias;
  66993. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66994. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66995. serializationObject.filteringQuality = this.filteringQuality;
  66996. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66997. serializationObject.renderList = [];
  66998. if (shadowMap.renderList) {
  66999. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67000. var mesh = shadowMap.renderList[meshIndex];
  67001. serializationObject.renderList.push(mesh.id);
  67002. }
  67003. }
  67004. return serializationObject;
  67005. };
  67006. /**
  67007. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67008. * @param parsedShadowGenerator The JSON object to parse
  67009. * @param scene The scene to create the shadow map for
  67010. * @returns The parsed shadow generator
  67011. */
  67012. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67013. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67014. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67015. var shadowMap = shadowGenerator.getShadowMap();
  67016. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67017. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67018. meshes.forEach(function (mesh) {
  67019. if (!shadowMap) {
  67020. return;
  67021. }
  67022. if (!shadowMap.renderList) {
  67023. shadowMap.renderList = [];
  67024. }
  67025. shadowMap.renderList.push(mesh);
  67026. });
  67027. }
  67028. if (parsedShadowGenerator.usePoissonSampling) {
  67029. shadowGenerator.usePoissonSampling = true;
  67030. }
  67031. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67032. shadowGenerator.useExponentialShadowMap = true;
  67033. }
  67034. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67035. shadowGenerator.useBlurExponentialShadowMap = true;
  67036. }
  67037. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67038. shadowGenerator.useCloseExponentialShadowMap = true;
  67039. }
  67040. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67041. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67042. }
  67043. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67044. shadowGenerator.usePercentageCloserFiltering = true;
  67045. }
  67046. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67047. shadowGenerator.useContactHardeningShadow = true;
  67048. }
  67049. if (parsedShadowGenerator.filteringQuality) {
  67050. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67051. }
  67052. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67053. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67054. }
  67055. // Backward compat
  67056. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67057. shadowGenerator.useExponentialShadowMap = true;
  67058. }
  67059. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67060. shadowGenerator.useBlurExponentialShadowMap = true;
  67061. }
  67062. if (parsedShadowGenerator.depthScale) {
  67063. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67064. }
  67065. if (parsedShadowGenerator.blurScale) {
  67066. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67067. }
  67068. if (parsedShadowGenerator.blurBoxOffset) {
  67069. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67070. }
  67071. if (parsedShadowGenerator.useKernelBlur) {
  67072. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67073. }
  67074. if (parsedShadowGenerator.blurKernel) {
  67075. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67076. }
  67077. if (parsedShadowGenerator.bias !== undefined) {
  67078. shadowGenerator.bias = parsedShadowGenerator.bias;
  67079. }
  67080. if (parsedShadowGenerator.normalBias !== undefined) {
  67081. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67082. }
  67083. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67084. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67085. }
  67086. if (parsedShadowGenerator.darkness) {
  67087. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67088. }
  67089. if (parsedShadowGenerator.transparencyShadow) {
  67090. shadowGenerator.setTransparencyShadow(true);
  67091. }
  67092. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67093. return shadowGenerator;
  67094. };
  67095. /**
  67096. * Shadow generator mode None: no filtering applied.
  67097. */
  67098. ShadowGenerator.FILTER_NONE = 0;
  67099. /**
  67100. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67101. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67102. */
  67103. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67104. /**
  67105. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67106. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67107. */
  67108. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67109. /**
  67110. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67111. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67112. */
  67113. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67114. /**
  67115. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67116. * edge artifacts on steep falloff.
  67117. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67118. */
  67119. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67120. /**
  67121. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67122. * edge artifacts on steep falloff.
  67123. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67124. */
  67125. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67126. /**
  67127. * Shadow generator mode PCF: Percentage Closer Filtering
  67128. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67129. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67130. */
  67131. ShadowGenerator.FILTER_PCF = 6;
  67132. /**
  67133. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67134. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67135. * Contact Hardening
  67136. */
  67137. ShadowGenerator.FILTER_PCSS = 7;
  67138. /**
  67139. * Reserved for PCF and PCSS
  67140. * Highest Quality.
  67141. *
  67142. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67143. *
  67144. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67145. */
  67146. ShadowGenerator.QUALITY_HIGH = 0;
  67147. /**
  67148. * Reserved for PCF and PCSS
  67149. * Good tradeoff for quality/perf cross devices
  67150. *
  67151. * Execute PCF on a 3*3 kernel.
  67152. *
  67153. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67154. */
  67155. ShadowGenerator.QUALITY_MEDIUM = 1;
  67156. /**
  67157. * Reserved for PCF and PCSS
  67158. * The lowest quality but the fastest.
  67159. *
  67160. * Execute PCF on a 1*1 kernel.
  67161. *
  67162. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67163. */
  67164. ShadowGenerator.QUALITY_LOW = 2;
  67165. return ShadowGenerator;
  67166. }());
  67167. BABYLON.ShadowGenerator = ShadowGenerator;
  67168. })(BABYLON || (BABYLON = {}));
  67169. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67170. var BABYLON;
  67171. (function (BABYLON) {
  67172. var DefaultLoadingScreen = /** @class */ (function () {
  67173. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67174. if (_loadingText === void 0) { _loadingText = ""; }
  67175. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67176. var _this = this;
  67177. this._renderingCanvas = _renderingCanvas;
  67178. this._loadingText = _loadingText;
  67179. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67180. // Resize
  67181. this._resizeLoadingUI = function () {
  67182. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67183. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67184. if (!_this._loadingDiv) {
  67185. return;
  67186. }
  67187. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67188. _this._loadingDiv.style.left = canvasRect.left + "px";
  67189. _this._loadingDiv.style.top = canvasRect.top + "px";
  67190. _this._loadingDiv.style.width = canvasRect.width + "px";
  67191. _this._loadingDiv.style.height = canvasRect.height + "px";
  67192. };
  67193. }
  67194. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67195. if (this._loadingDiv) {
  67196. // Do not add a loading screen if there is already one
  67197. return;
  67198. }
  67199. this._loadingDiv = document.createElement("div");
  67200. this._loadingDiv.id = "babylonjsLoadingDiv";
  67201. this._loadingDiv.style.opacity = "0";
  67202. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67203. this._loadingDiv.style.pointerEvents = "none";
  67204. // Loading text
  67205. this._loadingTextDiv = document.createElement("div");
  67206. this._loadingTextDiv.style.position = "absolute";
  67207. this._loadingTextDiv.style.left = "0";
  67208. this._loadingTextDiv.style.top = "50%";
  67209. this._loadingTextDiv.style.marginTop = "80px";
  67210. this._loadingTextDiv.style.width = "100%";
  67211. this._loadingTextDiv.style.height = "20px";
  67212. this._loadingTextDiv.style.fontFamily = "Arial";
  67213. this._loadingTextDiv.style.fontSize = "14px";
  67214. this._loadingTextDiv.style.color = "white";
  67215. this._loadingTextDiv.style.textAlign = "center";
  67216. this._loadingTextDiv.innerHTML = "Loading";
  67217. this._loadingDiv.appendChild(this._loadingTextDiv);
  67218. //set the predefined text
  67219. this._loadingTextDiv.innerHTML = this._loadingText;
  67220. // Generating keyframes
  67221. var style = document.createElement('style');
  67222. style.type = 'text/css';
  67223. 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 }";
  67224. style.innerHTML = keyFrames;
  67225. document.getElementsByTagName('head')[0].appendChild(style);
  67226. // Loading img
  67227. var imgBack = new Image();
  67228. 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";
  67229. imgBack.style.position = "absolute";
  67230. imgBack.style.left = "50%";
  67231. imgBack.style.top = "50%";
  67232. imgBack.style.marginLeft = "-60px";
  67233. imgBack.style.marginTop = "-60px";
  67234. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67235. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67236. imgBack.style.transformOrigin = "50% 50%";
  67237. imgBack.style.webkitTransformOrigin = "50% 50%";
  67238. this._loadingDiv.appendChild(imgBack);
  67239. this._resizeLoadingUI();
  67240. window.addEventListener("resize", this._resizeLoadingUI);
  67241. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67242. document.body.appendChild(this._loadingDiv);
  67243. this._loadingDiv.style.opacity = "1";
  67244. };
  67245. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67246. var _this = this;
  67247. if (!this._loadingDiv) {
  67248. return;
  67249. }
  67250. var onTransitionEnd = function () {
  67251. if (!_this._loadingDiv) {
  67252. return;
  67253. }
  67254. document.body.removeChild(_this._loadingDiv);
  67255. window.removeEventListener("resize", _this._resizeLoadingUI);
  67256. _this._loadingDiv = null;
  67257. };
  67258. this._loadingDiv.style.opacity = "0";
  67259. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67260. };
  67261. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67262. set: function (text) {
  67263. this._loadingText = text;
  67264. if (this._loadingTextDiv) {
  67265. this._loadingTextDiv.innerHTML = this._loadingText;
  67266. }
  67267. },
  67268. enumerable: true,
  67269. configurable: true
  67270. });
  67271. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67272. get: function () {
  67273. return this._loadingDivBackgroundColor;
  67274. },
  67275. set: function (color) {
  67276. this._loadingDivBackgroundColor = color;
  67277. if (!this._loadingDiv) {
  67278. return;
  67279. }
  67280. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67281. },
  67282. enumerable: true,
  67283. configurable: true
  67284. });
  67285. return DefaultLoadingScreen;
  67286. }());
  67287. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67288. })(BABYLON || (BABYLON = {}));
  67289. //# sourceMappingURL=babylon.loadingScreen.js.map
  67290. var BABYLON;
  67291. (function (BABYLON) {
  67292. var SceneLoaderProgressEvent = /** @class */ (function () {
  67293. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67294. this.lengthComputable = lengthComputable;
  67295. this.loaded = loaded;
  67296. this.total = total;
  67297. }
  67298. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67299. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67300. };
  67301. return SceneLoaderProgressEvent;
  67302. }());
  67303. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67304. var SceneLoader = /** @class */ (function () {
  67305. function SceneLoader() {
  67306. }
  67307. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67308. get: function () {
  67309. return 0;
  67310. },
  67311. enumerable: true,
  67312. configurable: true
  67313. });
  67314. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67315. get: function () {
  67316. return 1;
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67322. get: function () {
  67323. return 2;
  67324. },
  67325. enumerable: true,
  67326. configurable: true
  67327. });
  67328. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67329. get: function () {
  67330. return 3;
  67331. },
  67332. enumerable: true,
  67333. configurable: true
  67334. });
  67335. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67336. get: function () {
  67337. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67338. },
  67339. set: function (value) {
  67340. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67341. },
  67342. enumerable: true,
  67343. configurable: true
  67344. });
  67345. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67346. get: function () {
  67347. return SceneLoader._ShowLoadingScreen;
  67348. },
  67349. set: function (value) {
  67350. SceneLoader._ShowLoadingScreen = value;
  67351. },
  67352. enumerable: true,
  67353. configurable: true
  67354. });
  67355. Object.defineProperty(SceneLoader, "loggingLevel", {
  67356. get: function () {
  67357. return SceneLoader._loggingLevel;
  67358. },
  67359. set: function (value) {
  67360. SceneLoader._loggingLevel = value;
  67361. },
  67362. enumerable: true,
  67363. configurable: true
  67364. });
  67365. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67366. get: function () {
  67367. return SceneLoader._CleanBoneMatrixWeights;
  67368. },
  67369. set: function (value) {
  67370. SceneLoader._CleanBoneMatrixWeights = value;
  67371. },
  67372. enumerable: true,
  67373. configurable: true
  67374. });
  67375. SceneLoader._getDefaultPlugin = function () {
  67376. return SceneLoader._registeredPlugins[".babylon"];
  67377. };
  67378. SceneLoader._getPluginForExtension = function (extension) {
  67379. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67380. if (registeredPlugin) {
  67381. return registeredPlugin;
  67382. }
  67383. 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");
  67384. return SceneLoader._getDefaultPlugin();
  67385. };
  67386. SceneLoader._getPluginForDirectLoad = function (data) {
  67387. for (var extension in SceneLoader._registeredPlugins) {
  67388. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67389. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67390. return SceneLoader._registeredPlugins[extension];
  67391. }
  67392. }
  67393. return SceneLoader._getDefaultPlugin();
  67394. };
  67395. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67396. if (sceneFilename.name) {
  67397. sceneFilename = sceneFilename.name;
  67398. }
  67399. var queryStringPosition = sceneFilename.indexOf("?");
  67400. if (queryStringPosition !== -1) {
  67401. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67402. }
  67403. var dotPosition = sceneFilename.lastIndexOf(".");
  67404. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67405. return SceneLoader._getPluginForExtension(extension);
  67406. };
  67407. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67408. SceneLoader._getDirectLoad = function (sceneFilename) {
  67409. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67410. return sceneFilename.substr(5);
  67411. }
  67412. return null;
  67413. };
  67414. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67415. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67416. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67417. var plugin;
  67418. if (registeredPlugin.plugin.createPlugin) {
  67419. plugin = registeredPlugin.plugin.createPlugin();
  67420. }
  67421. else {
  67422. plugin = registeredPlugin.plugin;
  67423. }
  67424. var useArrayBuffer = registeredPlugin.isBinary;
  67425. var database;
  67426. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67427. var dataCallback = function (data, responseURL) {
  67428. if (scene.isDisposed) {
  67429. onError("Scene has been disposed");
  67430. return;
  67431. }
  67432. scene.database = database;
  67433. onSuccess(plugin, data, responseURL);
  67434. };
  67435. var request = null;
  67436. var pluginDisposed = false;
  67437. var onDisposeObservable = plugin.onDisposeObservable;
  67438. if (onDisposeObservable) {
  67439. onDisposeObservable.add(function () {
  67440. pluginDisposed = true;
  67441. if (request) {
  67442. request.abort();
  67443. request = null;
  67444. }
  67445. onDispose();
  67446. });
  67447. }
  67448. var manifestChecked = function () {
  67449. if (pluginDisposed) {
  67450. return;
  67451. }
  67452. var url = rootUrl + sceneFilename;
  67453. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67454. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67455. } : undefined, database, useArrayBuffer, function (request, exception) {
  67456. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67457. });
  67458. };
  67459. if (directLoad) {
  67460. dataCallback(directLoad);
  67461. return plugin;
  67462. }
  67463. if (rootUrl.indexOf("file:") === -1) {
  67464. var engine = scene.getEngine();
  67465. var canUseOfflineSupport = engine.enableOfflineSupport;
  67466. if (canUseOfflineSupport) {
  67467. // Also check for exceptions
  67468. var exceptionFound = false;
  67469. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67470. var regex = _a[_i];
  67471. if (regex.test(rootUrl + sceneFilename)) {
  67472. exceptionFound = true;
  67473. break;
  67474. }
  67475. }
  67476. canUseOfflineSupport = !exceptionFound;
  67477. }
  67478. if (canUseOfflineSupport) {
  67479. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67480. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67481. }
  67482. else {
  67483. manifestChecked();
  67484. }
  67485. }
  67486. // Loading file from disk via input file or drag'n'drop
  67487. else {
  67488. var fileOrString = sceneFilename;
  67489. if (fileOrString.name) { // File
  67490. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67491. }
  67492. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67493. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67494. }
  67495. else {
  67496. onError("Unable to find file named " + sceneFilename);
  67497. }
  67498. }
  67499. return plugin;
  67500. };
  67501. // Public functions
  67502. SceneLoader.GetPluginForExtension = function (extension) {
  67503. return SceneLoader._getPluginForExtension(extension).plugin;
  67504. };
  67505. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67506. return !!SceneLoader._registeredPlugins[extension];
  67507. };
  67508. SceneLoader.RegisterPlugin = function (plugin) {
  67509. if (typeof plugin.extensions === "string") {
  67510. var extension = plugin.extensions;
  67511. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67512. plugin: plugin,
  67513. isBinary: false
  67514. };
  67515. }
  67516. else {
  67517. var extensions = plugin.extensions;
  67518. Object.keys(extensions).forEach(function (extension) {
  67519. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67520. plugin: plugin,
  67521. isBinary: extensions[extension].isBinary
  67522. };
  67523. });
  67524. }
  67525. };
  67526. /**
  67527. * Import meshes into a scene
  67528. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67529. * @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)
  67530. * @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)
  67531. * @param scene the instance of BABYLON.Scene to append to
  67532. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67533. * @param onProgress a callback with a progress event for each file being loaded
  67534. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67535. * @param pluginExtension the extension used to determine the plugin
  67536. * @returns The loaded plugin
  67537. */
  67538. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67539. if (sceneFilename === void 0) { sceneFilename = ""; }
  67540. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67541. if (onSuccess === void 0) { onSuccess = null; }
  67542. if (onProgress === void 0) { onProgress = null; }
  67543. if (onError === void 0) { onError = null; }
  67544. if (pluginExtension === void 0) { pluginExtension = null; }
  67545. if (!scene) {
  67546. BABYLON.Tools.Error("No scene available to import mesh to");
  67547. return null;
  67548. }
  67549. if (!sceneFilename) {
  67550. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67551. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67552. }
  67553. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67554. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67555. return null;
  67556. }
  67557. var loadingToken = {};
  67558. scene._addPendingData(loadingToken);
  67559. var disposeHandler = function () {
  67560. scene._removePendingData(loadingToken);
  67561. };
  67562. var errorHandler = function (message, exception) {
  67563. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67564. if (onError) {
  67565. onError(scene, errorMessage, exception);
  67566. }
  67567. else {
  67568. BABYLON.Tools.Error(errorMessage);
  67569. // should the exception be thrown?
  67570. }
  67571. disposeHandler();
  67572. };
  67573. var progressHandler = onProgress ? function (event) {
  67574. try {
  67575. onProgress(event);
  67576. }
  67577. catch (e) {
  67578. errorHandler("Error in onProgress callback", e);
  67579. }
  67580. } : undefined;
  67581. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67582. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67583. if (onSuccess) {
  67584. try {
  67585. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67586. }
  67587. catch (e) {
  67588. errorHandler("Error in onSuccess callback", e);
  67589. }
  67590. }
  67591. scene._removePendingData(loadingToken);
  67592. };
  67593. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67594. if (plugin.rewriteRootURL) {
  67595. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67596. }
  67597. if (sceneFilename === "") {
  67598. if (sceneFilename === "") {
  67599. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67600. }
  67601. }
  67602. if (plugin.importMesh) {
  67603. var syncedPlugin = plugin;
  67604. var meshes = new Array();
  67605. var particleSystems = new Array();
  67606. var skeletons = new Array();
  67607. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67608. return;
  67609. }
  67610. scene.loadingPluginName = plugin.name;
  67611. successHandler(meshes, particleSystems, skeletons, []);
  67612. }
  67613. else {
  67614. var asyncedPlugin = plugin;
  67615. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67616. scene.loadingPluginName = plugin.name;
  67617. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67618. }).catch(function (error) {
  67619. errorHandler(error.message, error);
  67620. });
  67621. }
  67622. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67623. };
  67624. /**
  67625. * Import meshes into a scene
  67626. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67627. * @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)
  67628. * @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)
  67629. * @param scene the instance of BABYLON.Scene to append to
  67630. * @param onProgress a callback with a progress event for each file being loaded
  67631. * @param pluginExtension the extension used to determine the plugin
  67632. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67633. */
  67634. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67635. if (sceneFilename === void 0) { sceneFilename = ""; }
  67636. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67637. if (onProgress === void 0) { onProgress = null; }
  67638. if (pluginExtension === void 0) { pluginExtension = null; }
  67639. return new Promise(function (resolve, reject) {
  67640. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67641. resolve({
  67642. meshes: meshes,
  67643. particleSystems: particleSystems,
  67644. skeletons: skeletons,
  67645. animationGroups: animationGroups
  67646. });
  67647. }, onProgress, function (scene, message, exception) {
  67648. reject(exception || new Error(message));
  67649. }, pluginExtension);
  67650. });
  67651. };
  67652. /**
  67653. * Load a scene
  67654. * @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)
  67655. * @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)
  67656. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67657. * @param onSuccess a callback with the scene when import succeeds
  67658. * @param onProgress a callback with a progress event for each file being loaded
  67659. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67660. * @param pluginExtension the extension used to determine the plugin
  67661. * @returns The loaded plugin
  67662. */
  67663. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67664. if (onSuccess === void 0) { onSuccess = null; }
  67665. if (onProgress === void 0) { onProgress = null; }
  67666. if (onError === void 0) { onError = null; }
  67667. if (pluginExtension === void 0) { pluginExtension = null; }
  67668. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67669. };
  67670. /**
  67671. * Load a scene
  67672. * @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)
  67673. * @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)
  67674. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67675. * @param onProgress a callback with a progress event for each file being loaded
  67676. * @param pluginExtension the extension used to determine the plugin
  67677. * @returns The loaded scene
  67678. */
  67679. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67680. if (onProgress === void 0) { onProgress = null; }
  67681. if (pluginExtension === void 0) { pluginExtension = null; }
  67682. return new Promise(function (resolve, reject) {
  67683. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67684. resolve(scene);
  67685. }, onProgress, function (scene, message, exception) {
  67686. reject(exception || new Error(message));
  67687. }, pluginExtension);
  67688. });
  67689. };
  67690. /**
  67691. * Append a scene
  67692. * @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)
  67693. * @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)
  67694. * @param scene is the instance of BABYLON.Scene to append to
  67695. * @param onSuccess a callback with the scene when import succeeds
  67696. * @param onProgress a callback with a progress event for each file being loaded
  67697. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67698. * @param pluginExtension the extension used to determine the plugin
  67699. * @returns The loaded plugin
  67700. */
  67701. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67702. if (sceneFilename === void 0) { sceneFilename = ""; }
  67703. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67704. if (onSuccess === void 0) { onSuccess = null; }
  67705. if (onProgress === void 0) { onProgress = null; }
  67706. if (onError === void 0) { onError = null; }
  67707. if (pluginExtension === void 0) { pluginExtension = null; }
  67708. if (!scene) {
  67709. BABYLON.Tools.Error("No scene available to append to");
  67710. return null;
  67711. }
  67712. if (!sceneFilename) {
  67713. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67714. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67715. }
  67716. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67717. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67718. return null;
  67719. }
  67720. if (SceneLoader.ShowLoadingScreen) {
  67721. scene.getEngine().displayLoadingUI();
  67722. }
  67723. var loadingToken = {};
  67724. scene._addPendingData(loadingToken);
  67725. var disposeHandler = function () {
  67726. scene._removePendingData(loadingToken);
  67727. scene.getEngine().hideLoadingUI();
  67728. };
  67729. var errorHandler = function (message, exception) {
  67730. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67731. if (onError) {
  67732. onError(scene, errorMessage, exception);
  67733. }
  67734. else {
  67735. BABYLON.Tools.Error(errorMessage);
  67736. // should the exception be thrown?
  67737. }
  67738. disposeHandler();
  67739. };
  67740. var progressHandler = onProgress ? function (event) {
  67741. try {
  67742. onProgress(event);
  67743. }
  67744. catch (e) {
  67745. errorHandler("Error in onProgress callback", e);
  67746. }
  67747. } : undefined;
  67748. var successHandler = function () {
  67749. if (onSuccess) {
  67750. try {
  67751. onSuccess(scene);
  67752. }
  67753. catch (e) {
  67754. errorHandler("Error in onSuccess callback", e);
  67755. }
  67756. }
  67757. scene._removePendingData(loadingToken);
  67758. };
  67759. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67760. if (sceneFilename === "") {
  67761. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67762. }
  67763. if (plugin.load) {
  67764. var syncedPlugin = plugin;
  67765. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67766. return;
  67767. }
  67768. scene.loadingPluginName = plugin.name;
  67769. successHandler();
  67770. }
  67771. else {
  67772. var asyncedPlugin = plugin;
  67773. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67774. scene.loadingPluginName = plugin.name;
  67775. successHandler();
  67776. }).catch(function (error) {
  67777. errorHandler(error.message, error);
  67778. });
  67779. }
  67780. if (SceneLoader.ShowLoadingScreen) {
  67781. scene.executeWhenReady(function () {
  67782. scene.getEngine().hideLoadingUI();
  67783. });
  67784. }
  67785. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67786. };
  67787. /**
  67788. * Append a scene
  67789. * @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)
  67790. * @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)
  67791. * @param scene is the instance of BABYLON.Scene to append to
  67792. * @param onProgress a callback with a progress event for each file being loaded
  67793. * @param pluginExtension the extension used to determine the plugin
  67794. * @returns The given scene
  67795. */
  67796. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67797. if (sceneFilename === void 0) { sceneFilename = ""; }
  67798. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67799. if (onProgress === void 0) { onProgress = null; }
  67800. if (pluginExtension === void 0) { pluginExtension = null; }
  67801. return new Promise(function (resolve, reject) {
  67802. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67803. resolve(scene);
  67804. }, onProgress, function (scene, message, exception) {
  67805. reject(exception || new Error(message));
  67806. }, pluginExtension);
  67807. });
  67808. };
  67809. /**
  67810. * Load a scene into an asset container
  67811. * @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)
  67812. * @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)
  67813. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67814. * @param onSuccess a callback with the scene when import succeeds
  67815. * @param onProgress a callback with a progress event for each file being loaded
  67816. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67817. * @param pluginExtension the extension used to determine the plugin
  67818. * @returns The loaded plugin
  67819. */
  67820. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67821. if (sceneFilename === void 0) { sceneFilename = ""; }
  67822. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67823. if (onSuccess === void 0) { onSuccess = null; }
  67824. if (onProgress === void 0) { onProgress = null; }
  67825. if (onError === void 0) { onError = null; }
  67826. if (pluginExtension === void 0) { pluginExtension = null; }
  67827. if (!scene) {
  67828. BABYLON.Tools.Error("No scene available to load asset container to");
  67829. return null;
  67830. }
  67831. if (!sceneFilename) {
  67832. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67833. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67834. }
  67835. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67836. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67837. return null;
  67838. }
  67839. var loadingToken = {};
  67840. scene._addPendingData(loadingToken);
  67841. var disposeHandler = function () {
  67842. scene._removePendingData(loadingToken);
  67843. };
  67844. var errorHandler = function (message, exception) {
  67845. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67846. if (onError) {
  67847. onError(scene, errorMessage, exception);
  67848. }
  67849. else {
  67850. BABYLON.Tools.Error(errorMessage);
  67851. // should the exception be thrown?
  67852. }
  67853. disposeHandler();
  67854. };
  67855. var progressHandler = onProgress ? function (event) {
  67856. try {
  67857. onProgress(event);
  67858. }
  67859. catch (e) {
  67860. errorHandler("Error in onProgress callback", e);
  67861. }
  67862. } : undefined;
  67863. var successHandler = function (assets) {
  67864. if (onSuccess) {
  67865. try {
  67866. onSuccess(assets);
  67867. }
  67868. catch (e) {
  67869. errorHandler("Error in onSuccess callback", e);
  67870. }
  67871. }
  67872. scene._removePendingData(loadingToken);
  67873. };
  67874. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67875. if (plugin.loadAssetContainer) {
  67876. var syncedPlugin = plugin;
  67877. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67878. if (!assetContainer) {
  67879. return;
  67880. }
  67881. scene.loadingPluginName = plugin.name;
  67882. successHandler(assetContainer);
  67883. }
  67884. else if (plugin.loadAssetContainerAsync) {
  67885. var asyncedPlugin = plugin;
  67886. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67887. scene.loadingPluginName = plugin.name;
  67888. successHandler(assetContainer);
  67889. }).catch(function (error) {
  67890. errorHandler(error.message, error);
  67891. });
  67892. }
  67893. else {
  67894. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67895. }
  67896. if (SceneLoader.ShowLoadingScreen) {
  67897. scene.executeWhenReady(function () {
  67898. scene.getEngine().hideLoadingUI();
  67899. });
  67900. }
  67901. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67902. };
  67903. /**
  67904. * Load a scene into an asset container
  67905. * @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)
  67906. * @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)
  67907. * @param scene is the instance of BABYLON.Scene to append to
  67908. * @param onProgress a callback with a progress event for each file being loaded
  67909. * @param pluginExtension the extension used to determine the plugin
  67910. * @returns The loaded asset container
  67911. */
  67912. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67913. if (sceneFilename === void 0) { sceneFilename = ""; }
  67914. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67915. if (onProgress === void 0) { onProgress = null; }
  67916. if (pluginExtension === void 0) { pluginExtension = null; }
  67917. return new Promise(function (resolve, reject) {
  67918. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67919. resolve(assetContainer);
  67920. }, onProgress, function (scene, message, exception) {
  67921. reject(exception || new Error(message));
  67922. }, pluginExtension);
  67923. });
  67924. };
  67925. // Flags
  67926. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67927. SceneLoader._ShowLoadingScreen = true;
  67928. SceneLoader._CleanBoneMatrixWeights = false;
  67929. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67930. // Members
  67931. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67932. SceneLoader._registeredPlugins = {};
  67933. return SceneLoader;
  67934. }());
  67935. BABYLON.SceneLoader = SceneLoader;
  67936. ;
  67937. })(BABYLON || (BABYLON = {}));
  67938. //# sourceMappingURL=babylon.sceneLoader.js.map
  67939. var BABYLON;
  67940. (function (BABYLON) {
  67941. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67942. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67943. var parsedMaterial = parsedData.materials[index];
  67944. if (parsedMaterial.id === id) {
  67945. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67946. }
  67947. }
  67948. return null;
  67949. };
  67950. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67951. for (var i in names) {
  67952. if (mesh.name === names[i]) {
  67953. hierarchyIds.push(mesh.id);
  67954. return true;
  67955. }
  67956. }
  67957. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67958. hierarchyIds.push(mesh.id);
  67959. return true;
  67960. }
  67961. return false;
  67962. };
  67963. var logOperation = function (operation, producer) {
  67964. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67965. };
  67966. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67967. if (addToScene === void 0) { addToScene = false; }
  67968. var container = new BABYLON.AssetContainer(scene);
  67969. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67970. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67971. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67972. // and avoid problems with multiple concurrent .babylon loads.
  67973. var log = "importScene has failed JSON parse";
  67974. try {
  67975. var parsedData = JSON.parse(data);
  67976. log = "";
  67977. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67978. var index;
  67979. var cache;
  67980. // Lights
  67981. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67982. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67983. var parsedLight = parsedData.lights[index];
  67984. var light = BABYLON.Light.Parse(parsedLight, scene);
  67985. if (light) {
  67986. container.lights.push(light);
  67987. log += (index === 0 ? "\n\tLights:" : "");
  67988. log += "\n\t\t" + light.toString(fullDetails);
  67989. }
  67990. }
  67991. }
  67992. // Animations
  67993. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67994. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67995. var parsedAnimation = parsedData.animations[index];
  67996. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67997. scene.animations.push(animation);
  67998. container.animations.push(animation);
  67999. log += (index === 0 ? "\n\tAnimations:" : "");
  68000. log += "\n\t\t" + animation.toString(fullDetails);
  68001. }
  68002. }
  68003. // Materials
  68004. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68005. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68006. var parsedMaterial = parsedData.materials[index];
  68007. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68008. container.materials.push(mat);
  68009. log += (index === 0 ? "\n\tMaterials:" : "");
  68010. log += "\n\t\t" + mat.toString(fullDetails);
  68011. }
  68012. }
  68013. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68014. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68015. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68016. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68017. container.multiMaterials.push(mmat);
  68018. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68019. log += "\n\t\t" + mmat.toString(fullDetails);
  68020. }
  68021. }
  68022. // Morph targets
  68023. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68024. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68025. var managerData = _a[_i];
  68026. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68027. }
  68028. }
  68029. // Skeletons
  68030. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68031. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68032. var parsedSkeleton = parsedData.skeletons[index];
  68033. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68034. container.skeletons.push(skeleton);
  68035. log += (index === 0 ? "\n\tSkeletons:" : "");
  68036. log += "\n\t\t" + skeleton.toString(fullDetails);
  68037. }
  68038. }
  68039. // Geometries
  68040. var geometries = parsedData.geometries;
  68041. if (geometries !== undefined && geometries !== null) {
  68042. var addedGeometry = new Array();
  68043. // Boxes
  68044. var boxes = geometries.boxes;
  68045. if (boxes !== undefined && boxes !== null) {
  68046. for (index = 0, cache = boxes.length; index < cache; index++) {
  68047. var parsedBox = boxes[index];
  68048. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68049. }
  68050. }
  68051. // Spheres
  68052. var spheres = geometries.spheres;
  68053. if (spheres !== undefined && spheres !== null) {
  68054. for (index = 0, cache = spheres.length; index < cache; index++) {
  68055. var parsedSphere = spheres[index];
  68056. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68057. }
  68058. }
  68059. // Cylinders
  68060. var cylinders = geometries.cylinders;
  68061. if (cylinders !== undefined && cylinders !== null) {
  68062. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68063. var parsedCylinder = cylinders[index];
  68064. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68065. }
  68066. }
  68067. // Toruses
  68068. var toruses = geometries.toruses;
  68069. if (toruses !== undefined && toruses !== null) {
  68070. for (index = 0, cache = toruses.length; index < cache; index++) {
  68071. var parsedTorus = toruses[index];
  68072. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68073. }
  68074. }
  68075. // Grounds
  68076. var grounds = geometries.grounds;
  68077. if (grounds !== undefined && grounds !== null) {
  68078. for (index = 0, cache = grounds.length; index < cache; index++) {
  68079. var parsedGround = grounds[index];
  68080. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68081. }
  68082. }
  68083. // Planes
  68084. var planes = geometries.planes;
  68085. if (planes !== undefined && planes !== null) {
  68086. for (index = 0, cache = planes.length; index < cache; index++) {
  68087. var parsedPlane = planes[index];
  68088. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68089. }
  68090. }
  68091. // TorusKnots
  68092. var torusKnots = geometries.torusKnots;
  68093. if (torusKnots !== undefined && torusKnots !== null) {
  68094. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68095. var parsedTorusKnot = torusKnots[index];
  68096. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68097. }
  68098. }
  68099. // VertexData
  68100. var vertexData = geometries.vertexData;
  68101. if (vertexData !== undefined && vertexData !== null) {
  68102. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68103. var parsedVertexData = vertexData[index];
  68104. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68105. }
  68106. }
  68107. addedGeometry.forEach(function (g) {
  68108. if (g) {
  68109. container.geometries.push(g);
  68110. }
  68111. });
  68112. }
  68113. // Transform nodes
  68114. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68115. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68116. var parsedTransformNode = parsedData.transformNodes[index];
  68117. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68118. container.transformNodes.push(node);
  68119. }
  68120. }
  68121. // Meshes
  68122. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68123. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68124. var parsedMesh = parsedData.meshes[index];
  68125. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68126. container.meshes.push(mesh);
  68127. log += (index === 0 ? "\n\tMeshes:" : "");
  68128. log += "\n\t\t" + mesh.toString(fullDetails);
  68129. }
  68130. }
  68131. // Cameras
  68132. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68133. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68134. var parsedCamera = parsedData.cameras[index];
  68135. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68136. container.cameras.push(camera);
  68137. log += (index === 0 ? "\n\tCameras:" : "");
  68138. log += "\n\t\t" + camera.toString(fullDetails);
  68139. }
  68140. }
  68141. // Browsing all the graph to connect the dots
  68142. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68143. var camera = scene.cameras[index];
  68144. if (camera._waitingParentId) {
  68145. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68146. camera._waitingParentId = null;
  68147. }
  68148. }
  68149. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68150. var light_1 = scene.lights[index];
  68151. if (light_1 && light_1._waitingParentId) {
  68152. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68153. light_1._waitingParentId = null;
  68154. }
  68155. }
  68156. // Sounds
  68157. // TODO: add sound
  68158. var loadedSounds = [];
  68159. var loadedSound;
  68160. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68161. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68162. var parsedSound = parsedData.sounds[index];
  68163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68164. if (!parsedSound.url)
  68165. parsedSound.url = parsedSound.name;
  68166. if (!loadedSounds[parsedSound.url]) {
  68167. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68168. loadedSounds[parsedSound.url] = loadedSound;
  68169. container.sounds.push(loadedSound);
  68170. }
  68171. else {
  68172. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68173. }
  68174. }
  68175. else {
  68176. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68177. }
  68178. }
  68179. }
  68180. loadedSounds = [];
  68181. // Connect parents & children and parse actions
  68182. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68183. var transformNode = scene.transformNodes[index];
  68184. if (transformNode._waitingParentId) {
  68185. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68186. transformNode._waitingParentId = null;
  68187. }
  68188. }
  68189. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68190. var mesh = scene.meshes[index];
  68191. if (mesh._waitingParentId) {
  68192. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68193. mesh._waitingParentId = null;
  68194. }
  68195. if (mesh._waitingActions) {
  68196. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68197. mesh._waitingActions = null;
  68198. }
  68199. }
  68200. // freeze world matrix application
  68201. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68202. var currentMesh = scene.meshes[index];
  68203. if (currentMesh._waitingFreezeWorldMatrix) {
  68204. currentMesh.freezeWorldMatrix();
  68205. currentMesh._waitingFreezeWorldMatrix = null;
  68206. }
  68207. else {
  68208. currentMesh.computeWorldMatrix(true);
  68209. }
  68210. }
  68211. // Shadows
  68212. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68213. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68214. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68215. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68216. // SG would be available on their associated lights
  68217. }
  68218. }
  68219. // Lights exclusions / inclusions
  68220. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68221. var light_2 = scene.lights[index];
  68222. // Excluded check
  68223. if (light_2._excludedMeshesIds.length > 0) {
  68224. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68225. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68226. if (excludedMesh) {
  68227. light_2.excludedMeshes.push(excludedMesh);
  68228. }
  68229. }
  68230. light_2._excludedMeshesIds = [];
  68231. }
  68232. // Included check
  68233. if (light_2._includedOnlyMeshesIds.length > 0) {
  68234. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68235. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68236. if (includedOnlyMesh) {
  68237. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68238. }
  68239. }
  68240. light_2._includedOnlyMeshesIds = [];
  68241. }
  68242. }
  68243. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68244. // Actions (scene)
  68245. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68246. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68247. }
  68248. if (!addToScene) {
  68249. container.removeAllFromScene();
  68250. }
  68251. }
  68252. catch (err) {
  68253. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68254. if (onError) {
  68255. onError(msg, err);
  68256. }
  68257. else {
  68258. BABYLON.Tools.Log(msg);
  68259. throw err;
  68260. }
  68261. }
  68262. finally {
  68263. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68264. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68265. }
  68266. }
  68267. return container;
  68268. };
  68269. BABYLON.SceneLoader.RegisterPlugin({
  68270. name: "babylon.js",
  68271. extensions: ".babylon",
  68272. canDirectLoad: function (data) {
  68273. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68274. return true;
  68275. }
  68276. return false;
  68277. },
  68278. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68279. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68280. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68281. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68282. // and avoid problems with multiple concurrent .babylon loads.
  68283. var log = "importMesh has failed JSON parse";
  68284. try {
  68285. var parsedData = JSON.parse(data);
  68286. log = "";
  68287. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68288. if (!meshesNames) {
  68289. meshesNames = null;
  68290. }
  68291. else if (!Array.isArray(meshesNames)) {
  68292. meshesNames = [meshesNames];
  68293. }
  68294. var hierarchyIds = new Array();
  68295. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68296. var loadedSkeletonsIds = [];
  68297. var loadedMaterialsIds = [];
  68298. var index;
  68299. var cache;
  68300. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68301. var parsedMesh = parsedData.meshes[index];
  68302. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68303. if (meshesNames !== null) {
  68304. // Remove found mesh name from list.
  68305. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68306. }
  68307. //Geometry?
  68308. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68309. //does the file contain geometries?
  68310. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68311. //find the correct geometry and add it to the scene
  68312. var found = false;
  68313. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68314. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68315. return;
  68316. }
  68317. else {
  68318. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68319. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68320. switch (geometryType) {
  68321. case "boxes":
  68322. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68323. break;
  68324. case "spheres":
  68325. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68326. break;
  68327. case "cylinders":
  68328. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68329. break;
  68330. case "toruses":
  68331. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68332. break;
  68333. case "grounds":
  68334. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68335. break;
  68336. case "planes":
  68337. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68338. break;
  68339. case "torusKnots":
  68340. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68341. break;
  68342. case "vertexData":
  68343. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68344. break;
  68345. }
  68346. found = true;
  68347. }
  68348. });
  68349. }
  68350. });
  68351. if (found === false) {
  68352. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68353. }
  68354. }
  68355. }
  68356. // Material ?
  68357. if (parsedMesh.materialId) {
  68358. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68359. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68360. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68361. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68362. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68363. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68364. var subMatId = parsedMultiMaterial.materials[matIndex];
  68365. loadedMaterialsIds.push(subMatId);
  68366. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68367. if (mat) {
  68368. log += "\n\tMaterial " + mat.toString(fullDetails);
  68369. }
  68370. }
  68371. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68372. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68373. if (mmat) {
  68374. materialFound = true;
  68375. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68376. }
  68377. break;
  68378. }
  68379. }
  68380. }
  68381. if (materialFound === false) {
  68382. loadedMaterialsIds.push(parsedMesh.materialId);
  68383. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68384. if (!mat) {
  68385. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68386. }
  68387. else {
  68388. log += "\n\tMaterial " + mat.toString(fullDetails);
  68389. }
  68390. }
  68391. }
  68392. // Skeleton ?
  68393. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68394. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68395. if (skeletonAlreadyLoaded === false) {
  68396. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68397. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68398. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68399. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68400. skeletons.push(skeleton);
  68401. loadedSkeletonsIds.push(parsedSkeleton.id);
  68402. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68403. }
  68404. }
  68405. }
  68406. }
  68407. // Morph targets ?
  68408. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68409. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68410. var managerData = _a[_i];
  68411. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68412. }
  68413. }
  68414. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68415. meshes.push(mesh);
  68416. log += "\n\tMesh " + mesh.toString(fullDetails);
  68417. }
  68418. }
  68419. // Connecting parents
  68420. var currentMesh;
  68421. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68422. currentMesh = scene.meshes[index];
  68423. if (currentMesh._waitingParentId) {
  68424. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68425. currentMesh._waitingParentId = null;
  68426. }
  68427. }
  68428. // freeze and compute world matrix application
  68429. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68430. currentMesh = scene.meshes[index];
  68431. if (currentMesh._waitingFreezeWorldMatrix) {
  68432. currentMesh.freezeWorldMatrix();
  68433. currentMesh._waitingFreezeWorldMatrix = null;
  68434. }
  68435. else {
  68436. currentMesh.computeWorldMatrix(true);
  68437. }
  68438. }
  68439. }
  68440. // Particles
  68441. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68442. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  68443. if (parser) {
  68444. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68445. var parsedParticleSystem = parsedData.particleSystems[index];
  68446. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68447. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  68448. }
  68449. }
  68450. }
  68451. }
  68452. return true;
  68453. }
  68454. catch (err) {
  68455. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68456. if (onError) {
  68457. onError(msg, err);
  68458. }
  68459. else {
  68460. BABYLON.Tools.Log(msg);
  68461. throw err;
  68462. }
  68463. }
  68464. finally {
  68465. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68466. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68467. }
  68468. }
  68469. return false;
  68470. },
  68471. load: function (scene, data, rootUrl, onError) {
  68472. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68473. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68474. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68475. // and avoid problems with multiple concurrent .babylon loads.
  68476. var log = "importScene has failed JSON parse";
  68477. try {
  68478. var parsedData = JSON.parse(data);
  68479. log = "";
  68480. // Scene
  68481. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68482. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68483. }
  68484. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68485. scene.autoClear = parsedData.autoClear;
  68486. }
  68487. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68488. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68489. }
  68490. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68491. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68492. }
  68493. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68494. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68495. }
  68496. // Fog
  68497. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68498. scene.fogMode = parsedData.fogMode;
  68499. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68500. scene.fogStart = parsedData.fogStart;
  68501. scene.fogEnd = parsedData.fogEnd;
  68502. scene.fogDensity = parsedData.fogDensity;
  68503. log += "\tFog mode for scene: ";
  68504. switch (scene.fogMode) {
  68505. // getters not compiling, so using hardcoded
  68506. case 1:
  68507. log += "exp\n";
  68508. break;
  68509. case 2:
  68510. log += "exp2\n";
  68511. break;
  68512. case 3:
  68513. log += "linear\n";
  68514. break;
  68515. }
  68516. }
  68517. //Physics
  68518. if (parsedData.physicsEnabled) {
  68519. var physicsPlugin;
  68520. if (parsedData.physicsEngine === "cannon") {
  68521. physicsPlugin = new BABYLON.CannonJSPlugin();
  68522. }
  68523. else if (parsedData.physicsEngine === "oimo") {
  68524. physicsPlugin = new BABYLON.OimoJSPlugin();
  68525. }
  68526. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68527. //else - default engine, which is currently oimo
  68528. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68529. scene.enablePhysics(physicsGravity, physicsPlugin);
  68530. }
  68531. // Metadata
  68532. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68533. scene.metadata = parsedData.metadata;
  68534. }
  68535. //collisions, if defined. otherwise, default is true
  68536. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68537. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68538. }
  68539. scene.workerCollisions = !!parsedData.workerCollisions;
  68540. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68541. if (!container) {
  68542. return false;
  68543. }
  68544. if (parsedData.autoAnimate) {
  68545. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68546. }
  68547. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68548. scene.setActiveCameraByID(parsedData.activeCameraID);
  68549. }
  68550. // Environment texture
  68551. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68552. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68553. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68554. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68555. if (parsedData.environmentTextureRotationY) {
  68556. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68557. }
  68558. scene.environmentTexture = hdrTexture;
  68559. }
  68560. else {
  68561. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68562. if (parsedData.environmentTextureRotationY) {
  68563. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68564. }
  68565. scene.environmentTexture = cubeTexture;
  68566. }
  68567. if (parsedData.createDefaultSkybox === true) {
  68568. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68569. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68570. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68571. }
  68572. }
  68573. // Finish
  68574. return true;
  68575. }
  68576. catch (err) {
  68577. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68578. if (onError) {
  68579. onError(msg, err);
  68580. }
  68581. else {
  68582. BABYLON.Tools.Log(msg);
  68583. throw err;
  68584. }
  68585. }
  68586. finally {
  68587. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68588. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68589. }
  68590. }
  68591. return false;
  68592. },
  68593. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68594. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68595. return container;
  68596. }
  68597. });
  68598. })(BABYLON || (BABYLON = {}));
  68599. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68600. var BABYLON;
  68601. (function (BABYLON) {
  68602. var FilesInput = /** @class */ (function () {
  68603. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68604. this.onProcessFileCallback = function () { return true; };
  68605. this._engine = engine;
  68606. this._currentScene = scene;
  68607. this._sceneLoadedCallback = sceneLoadedCallback;
  68608. this._progressCallback = progressCallback;
  68609. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68610. this._textureLoadingCallback = textureLoadingCallback;
  68611. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68612. this._onReloadCallback = onReloadCallback;
  68613. this._errorCallback = errorCallback;
  68614. }
  68615. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68616. var _this = this;
  68617. if (elementToMonitor) {
  68618. this._elementToMonitor = elementToMonitor;
  68619. this._dragEnterHandler = function (e) { _this.drag(e); };
  68620. this._dragOverHandler = function (e) { _this.drag(e); };
  68621. this._dropHandler = function (e) { _this.drop(e); };
  68622. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68623. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68624. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68625. }
  68626. };
  68627. FilesInput.prototype.dispose = function () {
  68628. if (!this._elementToMonitor) {
  68629. return;
  68630. }
  68631. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68632. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68633. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68634. };
  68635. FilesInput.prototype.renderFunction = function () {
  68636. if (this._additionalRenderLoopLogicCallback) {
  68637. this._additionalRenderLoopLogicCallback();
  68638. }
  68639. if (this._currentScene) {
  68640. if (this._textureLoadingCallback) {
  68641. var remaining = this._currentScene.getWaitingItemsCount();
  68642. if (remaining > 0) {
  68643. this._textureLoadingCallback(remaining);
  68644. }
  68645. }
  68646. this._currentScene.render();
  68647. }
  68648. };
  68649. FilesInput.prototype.drag = function (e) {
  68650. e.stopPropagation();
  68651. e.preventDefault();
  68652. };
  68653. FilesInput.prototype.drop = function (eventDrop) {
  68654. eventDrop.stopPropagation();
  68655. eventDrop.preventDefault();
  68656. this.loadFiles(eventDrop);
  68657. };
  68658. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68659. var _this = this;
  68660. var reader = folder.createReader();
  68661. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68662. reader.readEntries(function (entries) {
  68663. remaining.count += entries.length;
  68664. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68665. var entry = entries_1[_i];
  68666. if (entry.isFile) {
  68667. entry.file(function (file) {
  68668. file.correctName = relativePath + file.name;
  68669. files.push(file);
  68670. if (--remaining.count === 0) {
  68671. callback();
  68672. }
  68673. });
  68674. }
  68675. else if (entry.isDirectory) {
  68676. _this._traverseFolder(entry, files, remaining, callback);
  68677. }
  68678. }
  68679. if (--remaining.count) {
  68680. callback();
  68681. }
  68682. });
  68683. };
  68684. FilesInput.prototype._processFiles = function (files) {
  68685. for (var i = 0; i < files.length; i++) {
  68686. var name = files[i].correctName.toLowerCase();
  68687. var extension = name.split('.').pop();
  68688. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68689. continue;
  68690. }
  68691. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68692. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68693. this._sceneFileToLoad = files[i];
  68694. }
  68695. else {
  68696. FilesInput.FilesToLoad[name] = files[i];
  68697. }
  68698. }
  68699. };
  68700. FilesInput.prototype.loadFiles = function (event) {
  68701. var _this = this;
  68702. if (this._startingProcessingFilesCallback)
  68703. this._startingProcessingFilesCallback();
  68704. // Handling data transfer via drag'n'drop
  68705. if (event && event.dataTransfer && event.dataTransfer.files) {
  68706. this._filesToLoad = event.dataTransfer.files;
  68707. }
  68708. // Handling files from input files
  68709. if (event && event.target && event.target.files) {
  68710. this._filesToLoad = event.target.files;
  68711. }
  68712. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68713. var files_1 = new Array();
  68714. var folders = [];
  68715. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68716. for (var i = 0; i < this._filesToLoad.length; i++) {
  68717. var fileToLoad = this._filesToLoad[i];
  68718. var name_1 = fileToLoad.name.toLowerCase();
  68719. var entry = void 0;
  68720. fileToLoad.correctName = name_1;
  68721. if (items) {
  68722. var item = items[i];
  68723. if (item.getAsEntry) {
  68724. entry = item.getAsEntry();
  68725. }
  68726. else if (item.webkitGetAsEntry) {
  68727. entry = item.webkitGetAsEntry();
  68728. }
  68729. }
  68730. if (!entry) {
  68731. files_1.push(fileToLoad);
  68732. }
  68733. else {
  68734. if (entry.isDirectory) {
  68735. folders.push(entry);
  68736. }
  68737. else {
  68738. files_1.push(fileToLoad);
  68739. }
  68740. }
  68741. }
  68742. if (folders.length === 0) {
  68743. this._processFiles(files_1);
  68744. this._processReload();
  68745. }
  68746. else {
  68747. var remaining = { count: folders.length };
  68748. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68749. var folder = folders_1[_i];
  68750. this._traverseFolder(folder, files_1, remaining, function () {
  68751. _this._processFiles(files_1);
  68752. if (remaining.count === 0) {
  68753. _this._processReload();
  68754. }
  68755. });
  68756. }
  68757. }
  68758. }
  68759. };
  68760. FilesInput.prototype._processReload = function () {
  68761. if (this._onReloadCallback) {
  68762. this._onReloadCallback(this._sceneFileToLoad);
  68763. }
  68764. else {
  68765. this.reload();
  68766. }
  68767. };
  68768. FilesInput.prototype.reload = function () {
  68769. var _this = this;
  68770. // If a scene file has been provided
  68771. if (this._sceneFileToLoad) {
  68772. if (this._currentScene) {
  68773. if (BABYLON.Tools.errorsCount > 0) {
  68774. BABYLON.Tools.ClearLogCache();
  68775. }
  68776. this._engine.stopRenderLoop();
  68777. }
  68778. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68779. if (_this._progressCallback) {
  68780. _this._progressCallback(progress);
  68781. }
  68782. }).then(function (scene) {
  68783. if (_this._currentScene) {
  68784. _this._currentScene.dispose();
  68785. }
  68786. _this._currentScene = scene;
  68787. if (_this._sceneLoadedCallback) {
  68788. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68789. }
  68790. // Wait for textures and shaders to be ready
  68791. _this._currentScene.executeWhenReady(function () {
  68792. _this._engine.runRenderLoop(function () {
  68793. _this.renderFunction();
  68794. });
  68795. });
  68796. }).catch(function (error) {
  68797. if (_this._errorCallback) {
  68798. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68799. }
  68800. });
  68801. }
  68802. else {
  68803. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68804. }
  68805. };
  68806. FilesInput.FilesToLoad = {};
  68807. return FilesInput;
  68808. }());
  68809. BABYLON.FilesInput = FilesInput;
  68810. })(BABYLON || (BABYLON = {}));
  68811. //# sourceMappingURL=babylon.filesInput.js.map
  68812. var BABYLON;
  68813. (function (BABYLON) {
  68814. /**
  68815. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68816. * The underlying implementation relies on an associative array to ensure the best performances.
  68817. * The value can be anything including 'null' but except 'undefined'
  68818. */
  68819. var StringDictionary = /** @class */ (function () {
  68820. function StringDictionary() {
  68821. this._count = 0;
  68822. this._data = {};
  68823. }
  68824. /**
  68825. * This will clear this dictionary and copy the content from the 'source' one.
  68826. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68827. * @param source the dictionary to take the content from and copy to this dictionary
  68828. */
  68829. StringDictionary.prototype.copyFrom = function (source) {
  68830. var _this = this;
  68831. this.clear();
  68832. source.forEach(function (t, v) { return _this.add(t, v); });
  68833. };
  68834. /**
  68835. * Get a value based from its key
  68836. * @param key the given key to get the matching value from
  68837. * @return the value if found, otherwise undefined is returned
  68838. */
  68839. StringDictionary.prototype.get = function (key) {
  68840. var val = this._data[key];
  68841. if (val !== undefined) {
  68842. return val;
  68843. }
  68844. return undefined;
  68845. };
  68846. /**
  68847. * Get a value from its key or add it if it doesn't exist.
  68848. * This method will ensure you that a given key/data will be present in the dictionary.
  68849. * @param key the given key to get the matching value from
  68850. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68851. * The factory will only be invoked if there's no data for the given key.
  68852. * @return the value corresponding to the key.
  68853. */
  68854. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68855. var val = this.get(key);
  68856. if (val !== undefined) {
  68857. return val;
  68858. }
  68859. val = factory(key);
  68860. if (val) {
  68861. this.add(key, val);
  68862. }
  68863. return val;
  68864. };
  68865. /**
  68866. * Get a value from its key if present in the dictionary otherwise add it
  68867. * @param key the key to get the value from
  68868. * @param val if there's no such key/value pair in the dictionary add it with this value
  68869. * @return the value corresponding to the key
  68870. */
  68871. StringDictionary.prototype.getOrAdd = function (key, val) {
  68872. var curVal = this.get(key);
  68873. if (curVal !== undefined) {
  68874. return curVal;
  68875. }
  68876. this.add(key, val);
  68877. return val;
  68878. };
  68879. /**
  68880. * Check if there's a given key in the dictionary
  68881. * @param key the key to check for
  68882. * @return true if the key is present, false otherwise
  68883. */
  68884. StringDictionary.prototype.contains = function (key) {
  68885. return this._data[key] !== undefined;
  68886. };
  68887. /**
  68888. * Add a new key and its corresponding value
  68889. * @param key the key to add
  68890. * @param value the value corresponding to the key
  68891. * @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
  68892. */
  68893. StringDictionary.prototype.add = function (key, value) {
  68894. if (this._data[key] !== undefined) {
  68895. return false;
  68896. }
  68897. this._data[key] = value;
  68898. ++this._count;
  68899. return true;
  68900. };
  68901. StringDictionary.prototype.set = function (key, value) {
  68902. if (this._data[key] === undefined) {
  68903. return false;
  68904. }
  68905. this._data[key] = value;
  68906. return true;
  68907. };
  68908. /**
  68909. * Get the element of the given key and remove it from the dictionary
  68910. * @param key
  68911. */
  68912. StringDictionary.prototype.getAndRemove = function (key) {
  68913. var val = this.get(key);
  68914. if (val !== undefined) {
  68915. delete this._data[key];
  68916. --this._count;
  68917. return val;
  68918. }
  68919. return null;
  68920. };
  68921. /**
  68922. * Remove a key/value from the dictionary.
  68923. * @param key the key to remove
  68924. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68925. */
  68926. StringDictionary.prototype.remove = function (key) {
  68927. if (this.contains(key)) {
  68928. delete this._data[key];
  68929. --this._count;
  68930. return true;
  68931. }
  68932. return false;
  68933. };
  68934. /**
  68935. * Clear the whole content of the dictionary
  68936. */
  68937. StringDictionary.prototype.clear = function () {
  68938. this._data = {};
  68939. this._count = 0;
  68940. };
  68941. Object.defineProperty(StringDictionary.prototype, "count", {
  68942. get: function () {
  68943. return this._count;
  68944. },
  68945. enumerable: true,
  68946. configurable: true
  68947. });
  68948. /**
  68949. * Execute a callback on each key/val of the dictionary.
  68950. * Note that you can remove any element in this dictionary in the callback implementation
  68951. * @param callback the callback to execute on a given key/value pair
  68952. */
  68953. StringDictionary.prototype.forEach = function (callback) {
  68954. for (var cur in this._data) {
  68955. var val = this._data[cur];
  68956. callback(cur, val);
  68957. }
  68958. };
  68959. /**
  68960. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68961. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68962. * Note that you can remove any element in this dictionary in the callback implementation
  68963. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68964. */
  68965. StringDictionary.prototype.first = function (callback) {
  68966. for (var cur in this._data) {
  68967. var val = this._data[cur];
  68968. var res = callback(cur, val);
  68969. if (res) {
  68970. return res;
  68971. }
  68972. }
  68973. return null;
  68974. };
  68975. return StringDictionary;
  68976. }());
  68977. BABYLON.StringDictionary = StringDictionary;
  68978. })(BABYLON || (BABYLON = {}));
  68979. //# sourceMappingURL=babylon.stringDictionary.js.map
  68980. var BABYLON;
  68981. (function (BABYLON) {
  68982. var Tags = /** @class */ (function () {
  68983. function Tags() {
  68984. }
  68985. Tags.EnableFor = function (obj) {
  68986. obj._tags = obj._tags || {};
  68987. obj.hasTags = function () {
  68988. return Tags.HasTags(obj);
  68989. };
  68990. obj.addTags = function (tagsString) {
  68991. return Tags.AddTagsTo(obj, tagsString);
  68992. };
  68993. obj.removeTags = function (tagsString) {
  68994. return Tags.RemoveTagsFrom(obj, tagsString);
  68995. };
  68996. obj.matchesTagsQuery = function (tagsQuery) {
  68997. return Tags.MatchesQuery(obj, tagsQuery);
  68998. };
  68999. };
  69000. Tags.DisableFor = function (obj) {
  69001. delete obj._tags;
  69002. delete obj.hasTags;
  69003. delete obj.addTags;
  69004. delete obj.removeTags;
  69005. delete obj.matchesTagsQuery;
  69006. };
  69007. Tags.HasTags = function (obj) {
  69008. if (!obj._tags) {
  69009. return false;
  69010. }
  69011. return !BABYLON.Tools.IsEmpty(obj._tags);
  69012. };
  69013. Tags.GetTags = function (obj, asString) {
  69014. if (asString === void 0) { asString = true; }
  69015. if (!obj._tags) {
  69016. return null;
  69017. }
  69018. if (asString) {
  69019. var tagsArray = [];
  69020. for (var tag in obj._tags) {
  69021. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69022. tagsArray.push(tag);
  69023. }
  69024. }
  69025. return tagsArray.join(" ");
  69026. }
  69027. else {
  69028. return obj._tags;
  69029. }
  69030. };
  69031. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69032. // a tag cannot start with '||', '&&', and '!'
  69033. // it cannot contain whitespaces
  69034. Tags.AddTagsTo = function (obj, tagsString) {
  69035. if (!tagsString) {
  69036. return;
  69037. }
  69038. if (typeof tagsString !== "string") {
  69039. return;
  69040. }
  69041. var tags = tagsString.split(" ");
  69042. tags.forEach(function (tag, index, array) {
  69043. Tags._AddTagTo(obj, tag);
  69044. });
  69045. };
  69046. Tags._AddTagTo = function (obj, tag) {
  69047. tag = tag.trim();
  69048. if (tag === "" || tag === "true" || tag === "false") {
  69049. return;
  69050. }
  69051. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69052. return;
  69053. }
  69054. Tags.EnableFor(obj);
  69055. obj._tags[tag] = true;
  69056. };
  69057. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69058. if (!Tags.HasTags(obj)) {
  69059. return;
  69060. }
  69061. var tags = tagsString.split(" ");
  69062. for (var t in tags) {
  69063. Tags._RemoveTagFrom(obj, tags[t]);
  69064. }
  69065. };
  69066. Tags._RemoveTagFrom = function (obj, tag) {
  69067. delete obj._tags[tag];
  69068. };
  69069. Tags.MatchesQuery = function (obj, tagsQuery) {
  69070. if (tagsQuery === undefined) {
  69071. return true;
  69072. }
  69073. if (tagsQuery === "") {
  69074. return Tags.HasTags(obj);
  69075. }
  69076. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69077. };
  69078. return Tags;
  69079. }());
  69080. BABYLON.Tags = Tags;
  69081. })(BABYLON || (BABYLON = {}));
  69082. //# sourceMappingURL=babylon.tags.js.map
  69083. var BABYLON;
  69084. (function (BABYLON) {
  69085. /**
  69086. * Class used to evalaute queries containing `and` and `or` operators
  69087. */
  69088. var AndOrNotEvaluator = /** @class */ (function () {
  69089. function AndOrNotEvaluator() {
  69090. }
  69091. /**
  69092. * Evaluate a query
  69093. * @param query defines the query to evaluate
  69094. * @param evaluateCallback defines the callback used to filter result
  69095. * @returns true if the query matches
  69096. */
  69097. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69098. if (!query.match(/\([^\(\)]*\)/g)) {
  69099. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69100. }
  69101. else {
  69102. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69103. // remove parenthesis
  69104. r = r.slice(1, r.length - 1);
  69105. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69106. });
  69107. }
  69108. if (query === "true") {
  69109. return true;
  69110. }
  69111. if (query === "false") {
  69112. return false;
  69113. }
  69114. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69115. };
  69116. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69117. evaluateCallback = evaluateCallback || (function (r) {
  69118. return r === "true" ? true : false;
  69119. });
  69120. var result;
  69121. var or = parenthesisContent.split("||");
  69122. for (var i in or) {
  69123. if (or.hasOwnProperty(i)) {
  69124. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69125. var and = ori.split("&&");
  69126. if (and.length > 1) {
  69127. for (var j = 0; j < and.length; ++j) {
  69128. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69129. if (andj !== "true" && andj !== "false") {
  69130. if (andj[0] === "!") {
  69131. result = !evaluateCallback(andj.substring(1));
  69132. }
  69133. else {
  69134. result = evaluateCallback(andj);
  69135. }
  69136. }
  69137. else {
  69138. result = andj === "true" ? true : false;
  69139. }
  69140. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69141. ori = "false";
  69142. break;
  69143. }
  69144. }
  69145. }
  69146. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69147. result = true;
  69148. break;
  69149. }
  69150. // result equals false (or undefined)
  69151. if (ori !== "true" && ori !== "false") {
  69152. if (ori[0] === "!") {
  69153. result = !evaluateCallback(ori.substring(1));
  69154. }
  69155. else {
  69156. result = evaluateCallback(ori);
  69157. }
  69158. }
  69159. else {
  69160. result = ori === "true" ? true : false;
  69161. }
  69162. }
  69163. }
  69164. // the whole parenthesis scope is replaced by 'true' or 'false'
  69165. return result ? "true" : "false";
  69166. };
  69167. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69168. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69169. // remove whitespaces
  69170. r = r.replace(/[\s]/g, function () { return ""; });
  69171. return r.length % 2 ? "!" : "";
  69172. });
  69173. booleanString = booleanString.trim();
  69174. if (booleanString === "!true") {
  69175. booleanString = "false";
  69176. }
  69177. else if (booleanString === "!false") {
  69178. booleanString = "true";
  69179. }
  69180. return booleanString;
  69181. };
  69182. return AndOrNotEvaluator;
  69183. }());
  69184. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69185. })(BABYLON || (BABYLON = {}));
  69186. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69187. var BABYLON;
  69188. (function (BABYLON) {
  69189. /**
  69190. * Class used to enable access to IndexedDB
  69191. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69192. */
  69193. var Database = /** @class */ (function () {
  69194. /**
  69195. * Creates a new Database
  69196. * @param urlToScene defines the url to load the scene
  69197. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69198. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69199. */
  69200. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69201. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69202. var _this = this;
  69203. // Handling various flavors of prefixed version of IndexedDB
  69204. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69205. this.callbackManifestChecked = callbackManifestChecked;
  69206. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69207. this.db = null;
  69208. this._enableSceneOffline = false;
  69209. this._enableTexturesOffline = false;
  69210. this.manifestVersionFound = 0;
  69211. this.mustUpdateRessources = false;
  69212. this.hasReachedQuota = false;
  69213. if (!Database.IDBStorageEnabled) {
  69214. this.callbackManifestChecked(true);
  69215. }
  69216. else {
  69217. if (disableManifestCheck) {
  69218. this._enableSceneOffline = true;
  69219. this._enableTexturesOffline = true;
  69220. this.manifestVersionFound = 1;
  69221. BABYLON.Tools.SetImmediate(function () {
  69222. _this.callbackManifestChecked(true);
  69223. });
  69224. }
  69225. else {
  69226. this._checkManifestFile();
  69227. }
  69228. }
  69229. }
  69230. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69231. /**
  69232. * Gets a boolean indicating if scene must be saved in the database
  69233. */
  69234. get: function () {
  69235. return this._enableSceneOffline;
  69236. },
  69237. enumerable: true,
  69238. configurable: true
  69239. });
  69240. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69241. /**
  69242. * Gets a boolean indicating if textures must be saved in the database
  69243. */
  69244. get: function () {
  69245. return this._enableTexturesOffline;
  69246. },
  69247. enumerable: true,
  69248. configurable: true
  69249. });
  69250. Database.prototype._checkManifestFile = function () {
  69251. var _this = this;
  69252. var noManifestFile = function () {
  69253. _this._enableSceneOffline = false;
  69254. _this._enableTexturesOffline = false;
  69255. _this.callbackManifestChecked(false);
  69256. };
  69257. var timeStampUsed = false;
  69258. var manifestURL = this.currentSceneUrl + ".manifest";
  69259. var xhr = new XMLHttpRequest();
  69260. if (navigator.onLine) {
  69261. // Adding a timestamp to by-pass browsers' cache
  69262. timeStampUsed = true;
  69263. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69264. }
  69265. xhr.open("GET", manifestURL, true);
  69266. xhr.addEventListener("load", function () {
  69267. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69268. try {
  69269. var manifestFile = JSON.parse(xhr.response);
  69270. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69271. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69272. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69273. _this.manifestVersionFound = manifestFile.version;
  69274. }
  69275. if (_this.callbackManifestChecked) {
  69276. _this.callbackManifestChecked(true);
  69277. }
  69278. }
  69279. catch (ex) {
  69280. noManifestFile();
  69281. }
  69282. }
  69283. else {
  69284. noManifestFile();
  69285. }
  69286. }, false);
  69287. xhr.addEventListener("error", function (event) {
  69288. if (timeStampUsed) {
  69289. timeStampUsed = false;
  69290. // Let's retry without the timeStamp
  69291. // It could fail when coupled with HTML5 Offline API
  69292. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69293. xhr.open("GET", retryManifestURL, true);
  69294. xhr.send();
  69295. }
  69296. else {
  69297. noManifestFile();
  69298. }
  69299. }, false);
  69300. try {
  69301. xhr.send();
  69302. }
  69303. catch (ex) {
  69304. BABYLON.Tools.Error("Error on XHR send request.");
  69305. this.callbackManifestChecked(false);
  69306. }
  69307. };
  69308. /**
  69309. * Open the database and make it available
  69310. * @param successCallback defines the callback to call on success
  69311. * @param errorCallback defines the callback to call on error
  69312. */
  69313. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69314. var _this = this;
  69315. var handleError = function () {
  69316. _this.isSupported = false;
  69317. if (errorCallback)
  69318. errorCallback();
  69319. };
  69320. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69321. // Your browser doesn't support IndexedDB
  69322. this.isSupported = false;
  69323. if (errorCallback)
  69324. errorCallback();
  69325. }
  69326. else {
  69327. // If the DB hasn't been opened or created yet
  69328. if (!this.db) {
  69329. this.hasReachedQuota = false;
  69330. this.isSupported = true;
  69331. var request = this.idbFactory.open("babylonjs", 1);
  69332. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69333. request.onerror = function (event) {
  69334. handleError();
  69335. };
  69336. // executes when a version change transaction cannot complete due to other active transactions
  69337. request.onblocked = function (event) {
  69338. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69339. handleError();
  69340. };
  69341. // DB has been opened successfully
  69342. request.onsuccess = function (event) {
  69343. _this.db = request.result;
  69344. successCallback();
  69345. };
  69346. // Initialization of the DB. Creating Scenes & Textures stores
  69347. request.onupgradeneeded = function (event) {
  69348. _this.db = (event.target).result;
  69349. if (_this.db) {
  69350. try {
  69351. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69352. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69353. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69354. }
  69355. catch (ex) {
  69356. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69357. handleError();
  69358. }
  69359. }
  69360. };
  69361. }
  69362. // DB has already been created and opened
  69363. else {
  69364. if (successCallback)
  69365. successCallback();
  69366. }
  69367. }
  69368. };
  69369. /**
  69370. * Loads an image from the database
  69371. * @param url defines the url to load from
  69372. * @param image defines the target DOM image
  69373. */
  69374. Database.prototype.loadImageFromDB = function (url, image) {
  69375. var _this = this;
  69376. var completeURL = Database._ReturnFullUrlLocation(url);
  69377. var saveAndLoadImage = function () {
  69378. if (!_this.hasReachedQuota && _this.db !== null) {
  69379. // the texture is not yet in the DB, let's try to save it
  69380. _this._saveImageIntoDBAsync(completeURL, image);
  69381. }
  69382. // If the texture is not in the DB and we've reached the DB quota limit
  69383. // let's load it directly from the web
  69384. else {
  69385. image.src = url;
  69386. }
  69387. };
  69388. if (!this.mustUpdateRessources) {
  69389. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69390. }
  69391. // First time we're download the images or update requested in the manifest file by a version change
  69392. else {
  69393. saveAndLoadImage();
  69394. }
  69395. };
  69396. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69397. if (this.isSupported && this.db !== null) {
  69398. var texture;
  69399. var transaction = this.db.transaction(["textures"]);
  69400. transaction.onabort = function (event) {
  69401. image.src = url;
  69402. };
  69403. transaction.oncomplete = function (event) {
  69404. var blobTextureURL;
  69405. if (texture) {
  69406. var URL = window.URL || window.webkitURL;
  69407. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69408. image.onerror = function () {
  69409. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69410. image.src = url;
  69411. };
  69412. image.src = blobTextureURL;
  69413. }
  69414. else {
  69415. notInDBCallback();
  69416. }
  69417. };
  69418. var getRequest = transaction.objectStore("textures").get(url);
  69419. getRequest.onsuccess = function (event) {
  69420. texture = (event.target).result;
  69421. };
  69422. getRequest.onerror = function (event) {
  69423. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69424. image.src = url;
  69425. };
  69426. }
  69427. else {
  69428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69429. image.src = url;
  69430. }
  69431. };
  69432. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69433. var _this = this;
  69434. if (this.isSupported) {
  69435. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69436. var generateBlobUrl = function () {
  69437. var blobTextureURL;
  69438. if (blob) {
  69439. var URL = window.URL || window.webkitURL;
  69440. try {
  69441. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69442. }
  69443. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69444. catch (ex) {
  69445. blobTextureURL = URL.createObjectURL(blob);
  69446. }
  69447. }
  69448. if (blobTextureURL) {
  69449. image.src = blobTextureURL;
  69450. }
  69451. };
  69452. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69453. var xhr = new XMLHttpRequest(), blob;
  69454. xhr.open("GET", url, true);
  69455. xhr.responseType = "blob";
  69456. xhr.addEventListener("load", function () {
  69457. if (xhr.status === 200 && _this.db) {
  69458. // Blob as response (XHR2)
  69459. blob = xhr.response;
  69460. var transaction = _this.db.transaction(["textures"], "readwrite");
  69461. // the transaction could abort because of a QuotaExceededError error
  69462. transaction.onabort = function (event) {
  69463. try {
  69464. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69465. var srcElement = (event.srcElement || event.target);
  69466. var error = srcElement.error;
  69467. if (error && error.name === "QuotaExceededError") {
  69468. _this.hasReachedQuota = true;
  69469. }
  69470. }
  69471. catch (ex) { }
  69472. generateBlobUrl();
  69473. };
  69474. transaction.oncomplete = function (event) {
  69475. generateBlobUrl();
  69476. };
  69477. var newTexture = { textureUrl: url, data: blob };
  69478. try {
  69479. // Put the blob into the dabase
  69480. var addRequest = transaction.objectStore("textures").put(newTexture);
  69481. addRequest.onsuccess = function (event) {
  69482. };
  69483. addRequest.onerror = function (event) {
  69484. generateBlobUrl();
  69485. };
  69486. }
  69487. catch (ex) {
  69488. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69489. if (ex.code === 25) {
  69490. Database.IsUASupportingBlobStorage = false;
  69491. }
  69492. image.src = url;
  69493. }
  69494. }
  69495. else {
  69496. image.src = url;
  69497. }
  69498. }, false);
  69499. xhr.addEventListener("error", function (event) {
  69500. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69501. image.src = url;
  69502. }, false);
  69503. xhr.send();
  69504. }
  69505. else {
  69506. image.src = url;
  69507. }
  69508. }
  69509. else {
  69510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69511. image.src = url;
  69512. }
  69513. };
  69514. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69515. var _this = this;
  69516. var updateVersion = function () {
  69517. // the version is not yet in the DB or we need to update it
  69518. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69519. };
  69520. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69521. };
  69522. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69523. var _this = this;
  69524. if (this.isSupported && this.db) {
  69525. var version;
  69526. try {
  69527. var transaction = this.db.transaction(["versions"]);
  69528. transaction.oncomplete = function (event) {
  69529. if (version) {
  69530. // If the version in the JSON file is different from the version in DB
  69531. if (_this.manifestVersionFound !== version.data) {
  69532. _this.mustUpdateRessources = true;
  69533. updateInDBCallback();
  69534. }
  69535. else {
  69536. callback(version.data);
  69537. }
  69538. }
  69539. // version was not found in DB
  69540. else {
  69541. _this.mustUpdateRessources = true;
  69542. updateInDBCallback();
  69543. }
  69544. };
  69545. transaction.onabort = function (event) {
  69546. callback(-1);
  69547. };
  69548. var getRequest = transaction.objectStore("versions").get(url);
  69549. getRequest.onsuccess = function (event) {
  69550. version = (event.target).result;
  69551. };
  69552. getRequest.onerror = function (event) {
  69553. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69554. callback(-1);
  69555. };
  69556. }
  69557. catch (ex) {
  69558. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69559. callback(-1);
  69560. }
  69561. }
  69562. else {
  69563. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69564. callback(-1);
  69565. }
  69566. };
  69567. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69568. var _this = this;
  69569. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69570. try {
  69571. // Open a transaction to the database
  69572. var transaction = this.db.transaction(["versions"], "readwrite");
  69573. // the transaction could abort because of a QuotaExceededError error
  69574. transaction.onabort = function (event) {
  69575. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69576. var error = event.srcElement['error'];
  69577. if (error && error.name === "QuotaExceededError") {
  69578. _this.hasReachedQuota = true;
  69579. }
  69580. }
  69581. catch (ex) { }
  69582. callback(-1);
  69583. };
  69584. transaction.oncomplete = function (event) {
  69585. callback(_this.manifestVersionFound);
  69586. };
  69587. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69588. // Put the scene into the database
  69589. var addRequest = transaction.objectStore("versions").put(newVersion);
  69590. addRequest.onsuccess = function (event) {
  69591. };
  69592. addRequest.onerror = function (event) {
  69593. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69594. };
  69595. }
  69596. catch (ex) {
  69597. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69598. callback(-1);
  69599. }
  69600. }
  69601. else {
  69602. callback(-1);
  69603. }
  69604. };
  69605. /**
  69606. * Loads a file from database
  69607. * @param url defines the URL to load from
  69608. * @param sceneLoaded defines a callback to call on success
  69609. * @param progressCallBack defines a callback to call when progress changed
  69610. * @param errorCallback defines a callback to call on error
  69611. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69612. */
  69613. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69614. var _this = this;
  69615. var completeUrl = Database._ReturnFullUrlLocation(url);
  69616. var saveAndLoadFile = function () {
  69617. // the scene is not yet in the DB, let's try to save it
  69618. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69619. };
  69620. this._checkVersionFromDB(completeUrl, function (version) {
  69621. if (version !== -1) {
  69622. if (!_this.mustUpdateRessources) {
  69623. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69624. }
  69625. else {
  69626. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69627. }
  69628. }
  69629. else {
  69630. if (errorCallback) {
  69631. errorCallback();
  69632. }
  69633. }
  69634. });
  69635. };
  69636. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69637. if (this.isSupported && this.db) {
  69638. var targetStore;
  69639. if (url.indexOf(".babylon") !== -1) {
  69640. targetStore = "scenes";
  69641. }
  69642. else {
  69643. targetStore = "textures";
  69644. }
  69645. var file;
  69646. var transaction = this.db.transaction([targetStore]);
  69647. transaction.oncomplete = function (event) {
  69648. if (file) {
  69649. callback(file.data);
  69650. }
  69651. // file was not found in DB
  69652. else {
  69653. notInDBCallback();
  69654. }
  69655. };
  69656. transaction.onabort = function (event) {
  69657. notInDBCallback();
  69658. };
  69659. var getRequest = transaction.objectStore(targetStore).get(url);
  69660. getRequest.onsuccess = function (event) {
  69661. file = (event.target).result;
  69662. };
  69663. getRequest.onerror = function (event) {
  69664. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69665. notInDBCallback();
  69666. };
  69667. }
  69668. else {
  69669. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69670. callback();
  69671. }
  69672. };
  69673. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  69674. var _this = this;
  69675. if (this.isSupported) {
  69676. var targetStore;
  69677. if (url.indexOf(".babylon") !== -1) {
  69678. targetStore = "scenes";
  69679. }
  69680. else {
  69681. targetStore = "textures";
  69682. }
  69683. // Create XHR
  69684. var xhr = new XMLHttpRequest();
  69685. var fileData;
  69686. xhr.open("GET", url, true);
  69687. if (useArrayBuffer) {
  69688. xhr.responseType = "arraybuffer";
  69689. }
  69690. if (progressCallback) {
  69691. xhr.onprogress = progressCallback;
  69692. }
  69693. xhr.addEventListener("load", function () {
  69694. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  69695. // Blob as response (XHR2)
  69696. //fileData = xhr.responseText;
  69697. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69698. if (!_this.hasReachedQuota && _this.db) {
  69699. // Open a transaction to the database
  69700. var transaction = _this.db.transaction([targetStore], "readwrite");
  69701. // the transaction could abort because of a QuotaExceededError error
  69702. transaction.onabort = function (event) {
  69703. try {
  69704. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69705. var error = event.srcElement['error'];
  69706. if (error && error.name === "QuotaExceededError") {
  69707. _this.hasReachedQuota = true;
  69708. }
  69709. }
  69710. catch (ex) { }
  69711. callback(fileData);
  69712. };
  69713. transaction.oncomplete = function (event) {
  69714. callback(fileData);
  69715. };
  69716. var newFile;
  69717. if (targetStore === "scenes") {
  69718. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69719. }
  69720. else {
  69721. newFile = { textureUrl: url, data: fileData };
  69722. }
  69723. try {
  69724. // Put the scene into the database
  69725. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69726. addRequest.onsuccess = function (event) {
  69727. };
  69728. addRequest.onerror = function (event) {
  69729. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69730. };
  69731. }
  69732. catch (ex) {
  69733. callback(fileData);
  69734. }
  69735. }
  69736. else {
  69737. callback(fileData);
  69738. }
  69739. }
  69740. else {
  69741. if (xhr.status >= 400 && errorCallback) {
  69742. errorCallback(xhr);
  69743. }
  69744. else {
  69745. callback();
  69746. }
  69747. }
  69748. }, false);
  69749. xhr.addEventListener("error", function (event) {
  69750. BABYLON.Tools.Error("error on XHR request.");
  69751. callback();
  69752. }, false);
  69753. xhr.send();
  69754. }
  69755. else {
  69756. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69757. callback();
  69758. }
  69759. };
  69760. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69761. Database.IsUASupportingBlobStorage = true;
  69762. /** Gets a boolean indicating if Database storate is enabled */
  69763. Database.IDBStorageEnabled = true;
  69764. Database._ParseURL = function (url) {
  69765. var a = document.createElement('a');
  69766. a.href = url;
  69767. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69768. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69769. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69770. return absLocation;
  69771. };
  69772. Database._ReturnFullUrlLocation = function (url) {
  69773. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69774. return (Database._ParseURL(window.location.href) + url);
  69775. }
  69776. else {
  69777. return url;
  69778. }
  69779. };
  69780. return Database;
  69781. }());
  69782. BABYLON.Database = Database;
  69783. })(BABYLON || (BABYLON = {}));
  69784. //# sourceMappingURL=babylon.database.js.map
  69785. var BABYLON;
  69786. (function (BABYLON) {
  69787. var FresnelParameters = /** @class */ (function () {
  69788. function FresnelParameters() {
  69789. this._isEnabled = true;
  69790. this.leftColor = BABYLON.Color3.White();
  69791. this.rightColor = BABYLON.Color3.Black();
  69792. this.bias = 0;
  69793. this.power = 1;
  69794. }
  69795. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69796. get: function () {
  69797. return this._isEnabled;
  69798. },
  69799. set: function (value) {
  69800. if (this._isEnabled === value) {
  69801. return;
  69802. }
  69803. this._isEnabled = value;
  69804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69805. },
  69806. enumerable: true,
  69807. configurable: true
  69808. });
  69809. FresnelParameters.prototype.clone = function () {
  69810. var newFresnelParameters = new FresnelParameters();
  69811. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69812. return newFresnelParameters;
  69813. };
  69814. FresnelParameters.prototype.serialize = function () {
  69815. var serializationObject = {};
  69816. serializationObject.isEnabled = this.isEnabled;
  69817. serializationObject.leftColor = this.leftColor.asArray();
  69818. serializationObject.rightColor = this.rightColor.asArray();
  69819. serializationObject.bias = this.bias;
  69820. serializationObject.power = this.power;
  69821. return serializationObject;
  69822. };
  69823. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69824. var fresnelParameters = new FresnelParameters();
  69825. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69826. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69827. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69828. fresnelParameters.bias = parsedFresnelParameters.bias;
  69829. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69830. return fresnelParameters;
  69831. };
  69832. return FresnelParameters;
  69833. }());
  69834. BABYLON.FresnelParameters = FresnelParameters;
  69835. })(BABYLON || (BABYLON = {}));
  69836. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69837. var BABYLON;
  69838. (function (BABYLON) {
  69839. var MultiMaterial = /** @class */ (function (_super) {
  69840. __extends(MultiMaterial, _super);
  69841. function MultiMaterial(name, scene) {
  69842. var _this = _super.call(this, name, scene, true) || this;
  69843. scene.multiMaterials.push(_this);
  69844. _this.subMaterials = new Array();
  69845. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69846. return _this;
  69847. }
  69848. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69849. get: function () {
  69850. return this._subMaterials;
  69851. },
  69852. set: function (value) {
  69853. this._subMaterials = value;
  69854. this._hookArray(value);
  69855. },
  69856. enumerable: true,
  69857. configurable: true
  69858. });
  69859. MultiMaterial.prototype._hookArray = function (array) {
  69860. var _this = this;
  69861. var oldPush = array.push;
  69862. array.push = function () {
  69863. var items = [];
  69864. for (var _i = 0; _i < arguments.length; _i++) {
  69865. items[_i] = arguments[_i];
  69866. }
  69867. var result = oldPush.apply(array, items);
  69868. _this._markAllSubMeshesAsTexturesDirty();
  69869. return result;
  69870. };
  69871. var oldSplice = array.splice;
  69872. array.splice = function (index, deleteCount) {
  69873. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69874. _this._markAllSubMeshesAsTexturesDirty();
  69875. return deleted;
  69876. };
  69877. };
  69878. // Properties
  69879. MultiMaterial.prototype.getSubMaterial = function (index) {
  69880. if (index < 0 || index >= this.subMaterials.length) {
  69881. return this.getScene().defaultMaterial;
  69882. }
  69883. return this.subMaterials[index];
  69884. };
  69885. MultiMaterial.prototype.getActiveTextures = function () {
  69886. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69887. if (subMaterial) {
  69888. return subMaterial.getActiveTextures();
  69889. }
  69890. else {
  69891. return [];
  69892. }
  69893. }));
  69894. var _a;
  69895. };
  69896. // Methods
  69897. MultiMaterial.prototype.getClassName = function () {
  69898. return "MultiMaterial";
  69899. };
  69900. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69901. for (var index = 0; index < this.subMaterials.length; index++) {
  69902. var subMaterial = this.subMaterials[index];
  69903. if (subMaterial) {
  69904. if (subMaterial.storeEffectOnSubMeshes) {
  69905. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69906. return false;
  69907. }
  69908. continue;
  69909. }
  69910. if (!subMaterial.isReady(mesh)) {
  69911. return false;
  69912. }
  69913. }
  69914. }
  69915. return true;
  69916. };
  69917. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69918. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69919. for (var index = 0; index < this.subMaterials.length; index++) {
  69920. var subMaterial = null;
  69921. var current = this.subMaterials[index];
  69922. if (cloneChildren && current) {
  69923. subMaterial = current.clone(name + "-" + current.name);
  69924. }
  69925. else {
  69926. subMaterial = this.subMaterials[index];
  69927. }
  69928. newMultiMaterial.subMaterials.push(subMaterial);
  69929. }
  69930. return newMultiMaterial;
  69931. };
  69932. MultiMaterial.prototype.serialize = function () {
  69933. var serializationObject = {};
  69934. serializationObject.name = this.name;
  69935. serializationObject.id = this.id;
  69936. if (BABYLON.Tags) {
  69937. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69938. }
  69939. serializationObject.materials = [];
  69940. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69941. var subMat = this.subMaterials[matIndex];
  69942. if (subMat) {
  69943. serializationObject.materials.push(subMat.id);
  69944. }
  69945. else {
  69946. serializationObject.materials.push(null);
  69947. }
  69948. }
  69949. return serializationObject;
  69950. };
  69951. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69952. var scene = this.getScene();
  69953. if (!scene) {
  69954. return;
  69955. }
  69956. var index = scene.multiMaterials.indexOf(this);
  69957. if (index >= 0) {
  69958. scene.multiMaterials.splice(index, 1);
  69959. }
  69960. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69961. };
  69962. return MultiMaterial;
  69963. }(BABYLON.Material));
  69964. BABYLON.MultiMaterial = MultiMaterial;
  69965. })(BABYLON || (BABYLON = {}));
  69966. //# sourceMappingURL=babylon.multiMaterial.js.map
  69967. var BABYLON;
  69968. (function (BABYLON) {
  69969. var FreeCameraTouchInput = /** @class */ (function () {
  69970. function FreeCameraTouchInput() {
  69971. this._offsetX = null;
  69972. this._offsetY = null;
  69973. this._pointerPressed = new Array();
  69974. this.touchAngularSensibility = 200000.0;
  69975. this.touchMoveSensibility = 250.0;
  69976. }
  69977. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69978. var _this = this;
  69979. var previousPosition = null;
  69980. if (this._pointerInput === undefined) {
  69981. this._onLostFocus = function (evt) {
  69982. _this._offsetX = null;
  69983. _this._offsetY = null;
  69984. };
  69985. this._pointerInput = function (p, s) {
  69986. var evt = p.event;
  69987. if (evt.pointerType === "mouse") {
  69988. return;
  69989. }
  69990. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69991. if (!noPreventDefault) {
  69992. evt.preventDefault();
  69993. }
  69994. _this._pointerPressed.push(evt.pointerId);
  69995. if (_this._pointerPressed.length !== 1) {
  69996. return;
  69997. }
  69998. previousPosition = {
  69999. x: evt.clientX,
  70000. y: evt.clientY
  70001. };
  70002. }
  70003. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70004. if (!noPreventDefault) {
  70005. evt.preventDefault();
  70006. }
  70007. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70008. if (index === -1) {
  70009. return;
  70010. }
  70011. _this._pointerPressed.splice(index, 1);
  70012. if (index != 0) {
  70013. return;
  70014. }
  70015. previousPosition = null;
  70016. _this._offsetX = null;
  70017. _this._offsetY = null;
  70018. }
  70019. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70020. if (!noPreventDefault) {
  70021. evt.preventDefault();
  70022. }
  70023. if (!previousPosition) {
  70024. return;
  70025. }
  70026. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70027. if (index != 0) {
  70028. return;
  70029. }
  70030. _this._offsetX = evt.clientX - previousPosition.x;
  70031. _this._offsetY = -(evt.clientY - previousPosition.y);
  70032. }
  70033. };
  70034. }
  70035. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70036. if (this._onLostFocus) {
  70037. element.addEventListener("blur", this._onLostFocus);
  70038. }
  70039. };
  70040. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70041. if (this._pointerInput && element) {
  70042. if (this._observer) {
  70043. this.camera.getScene().onPointerObservable.remove(this._observer);
  70044. this._observer = null;
  70045. }
  70046. if (this._onLostFocus) {
  70047. element.removeEventListener("blur", this._onLostFocus);
  70048. this._onLostFocus = null;
  70049. }
  70050. this._pointerPressed = [];
  70051. this._offsetX = null;
  70052. this._offsetY = null;
  70053. }
  70054. };
  70055. FreeCameraTouchInput.prototype.checkInputs = function () {
  70056. if (this._offsetX && this._offsetY) {
  70057. var camera = this.camera;
  70058. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70059. if (this._pointerPressed.length > 1) {
  70060. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70061. }
  70062. else {
  70063. var speed = camera._computeLocalCameraSpeed();
  70064. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70065. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70066. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70067. }
  70068. }
  70069. };
  70070. FreeCameraTouchInput.prototype.getClassName = function () {
  70071. return "FreeCameraTouchInput";
  70072. };
  70073. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70074. return "touch";
  70075. };
  70076. __decorate([
  70077. BABYLON.serialize()
  70078. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70079. __decorate([
  70080. BABYLON.serialize()
  70081. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70082. return FreeCameraTouchInput;
  70083. }());
  70084. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70085. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70086. })(BABYLON || (BABYLON = {}));
  70087. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70088. var BABYLON;
  70089. (function (BABYLON) {
  70090. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  70091. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  70092. });
  70093. // We're mainly based on the logic defined into the FreeCamera code
  70094. var TouchCamera = /** @class */ (function (_super) {
  70095. __extends(TouchCamera, _super);
  70096. //-- end properties for backward compatibility for inputs
  70097. function TouchCamera(name, position, scene) {
  70098. var _this = _super.call(this, name, position, scene) || this;
  70099. _this.inputs.addTouch();
  70100. _this._setupInputs();
  70101. return _this;
  70102. }
  70103. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70104. //-- Begin properties for backward compatibility for inputs
  70105. get: function () {
  70106. var touch = this.inputs.attached["touch"];
  70107. if (touch)
  70108. return touch.touchAngularSensibility;
  70109. return 0;
  70110. },
  70111. set: function (value) {
  70112. var touch = this.inputs.attached["touch"];
  70113. if (touch)
  70114. touch.touchAngularSensibility = value;
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70120. get: function () {
  70121. var touch = this.inputs.attached["touch"];
  70122. if (touch)
  70123. return touch.touchMoveSensibility;
  70124. return 0;
  70125. },
  70126. set: function (value) {
  70127. var touch = this.inputs.attached["touch"];
  70128. if (touch)
  70129. touch.touchMoveSensibility = value;
  70130. },
  70131. enumerable: true,
  70132. configurable: true
  70133. });
  70134. TouchCamera.prototype.getClassName = function () {
  70135. return "TouchCamera";
  70136. };
  70137. TouchCamera.prototype._setupInputs = function () {
  70138. var mouse = this.inputs.attached["mouse"];
  70139. if (mouse) {
  70140. mouse.touchEnabled = false;
  70141. }
  70142. };
  70143. return TouchCamera;
  70144. }(BABYLON.FreeCamera));
  70145. BABYLON.TouchCamera = TouchCamera;
  70146. })(BABYLON || (BABYLON = {}));
  70147. //# sourceMappingURL=babylon.touchCamera.js.map
  70148. var BABYLON;
  70149. (function (BABYLON) {
  70150. var ProceduralTexture = /** @class */ (function (_super) {
  70151. __extends(ProceduralTexture, _super);
  70152. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70153. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70154. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70155. if (isCube === void 0) { isCube = false; }
  70156. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70157. _this.isCube = isCube;
  70158. _this.isEnabled = true;
  70159. _this._currentRefreshId = -1;
  70160. _this._refreshRate = 1;
  70161. _this._vertexBuffers = {};
  70162. _this._uniforms = new Array();
  70163. _this._samplers = new Array();
  70164. _this._textures = {};
  70165. _this._floats = {};
  70166. _this._floatsArrays = {};
  70167. _this._colors3 = {};
  70168. _this._colors4 = {};
  70169. _this._vectors2 = {};
  70170. _this._vectors3 = {};
  70171. _this._matrices = {};
  70172. _this._fallbackTextureUsed = false;
  70173. scene.proceduralTextures.push(_this);
  70174. _this._engine = scene.getEngine();
  70175. _this.name = name;
  70176. _this.isRenderTarget = true;
  70177. _this._size = size;
  70178. _this._generateMipMaps = generateMipMaps;
  70179. _this.setFragment(fragment);
  70180. _this._fallbackTexture = fallbackTexture;
  70181. if (isCube) {
  70182. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70183. _this.setFloat("face", 0);
  70184. }
  70185. else {
  70186. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70187. }
  70188. // VBO
  70189. var vertices = [];
  70190. vertices.push(1, 1);
  70191. vertices.push(-1, 1);
  70192. vertices.push(-1, -1);
  70193. vertices.push(1, -1);
  70194. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70195. _this._createIndexBuffer();
  70196. return _this;
  70197. }
  70198. ProceduralTexture.prototype._createIndexBuffer = function () {
  70199. var engine = this._engine;
  70200. // Indices
  70201. var indices = [];
  70202. indices.push(0);
  70203. indices.push(1);
  70204. indices.push(2);
  70205. indices.push(0);
  70206. indices.push(2);
  70207. indices.push(3);
  70208. this._indexBuffer = engine.createIndexBuffer(indices);
  70209. };
  70210. ProceduralTexture.prototype._rebuild = function () {
  70211. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70212. if (vb) {
  70213. vb._rebuild();
  70214. }
  70215. this._createIndexBuffer();
  70216. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70217. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70218. }
  70219. };
  70220. ProceduralTexture.prototype.reset = function () {
  70221. if (this._effect === undefined) {
  70222. return;
  70223. }
  70224. var engine = this._engine;
  70225. engine._releaseEffect(this._effect);
  70226. };
  70227. ProceduralTexture.prototype.isReady = function () {
  70228. var _this = this;
  70229. var engine = this._engine;
  70230. var shaders;
  70231. if (!this._fragment) {
  70232. return false;
  70233. }
  70234. if (this._fallbackTextureUsed) {
  70235. return true;
  70236. }
  70237. if (this._fragment.fragmentElement !== undefined) {
  70238. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70239. }
  70240. else {
  70241. shaders = { vertex: "procedural", fragment: this._fragment };
  70242. }
  70243. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70244. _this.releaseInternalTexture();
  70245. if (_this._fallbackTexture) {
  70246. _this._texture = _this._fallbackTexture._texture;
  70247. if (_this._texture) {
  70248. _this._texture.incrementReferences();
  70249. }
  70250. }
  70251. _this._fallbackTextureUsed = true;
  70252. });
  70253. return this._effect.isReady();
  70254. };
  70255. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70256. this._currentRefreshId = -1;
  70257. };
  70258. ProceduralTexture.prototype.setFragment = function (fragment) {
  70259. this._fragment = fragment;
  70260. };
  70261. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70262. get: function () {
  70263. return this._refreshRate;
  70264. },
  70265. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70266. set: function (value) {
  70267. this._refreshRate = value;
  70268. this.resetRefreshCounter();
  70269. },
  70270. enumerable: true,
  70271. configurable: true
  70272. });
  70273. ProceduralTexture.prototype._shouldRender = function () {
  70274. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70275. return false;
  70276. }
  70277. if (this._fallbackTextureUsed) {
  70278. return false;
  70279. }
  70280. if (this._currentRefreshId === -1) { // At least render once
  70281. this._currentRefreshId = 1;
  70282. return true;
  70283. }
  70284. if (this.refreshRate === this._currentRefreshId) {
  70285. this._currentRefreshId = 1;
  70286. return true;
  70287. }
  70288. this._currentRefreshId++;
  70289. return false;
  70290. };
  70291. ProceduralTexture.prototype.getRenderSize = function () {
  70292. return this._size;
  70293. };
  70294. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70295. if (this._fallbackTextureUsed) {
  70296. return;
  70297. }
  70298. this.releaseInternalTexture();
  70299. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70300. // Update properties
  70301. this._size = size;
  70302. this._generateMipMaps = generateMipMaps;
  70303. };
  70304. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70305. if (this._uniforms.indexOf(uniformName) === -1) {
  70306. this._uniforms.push(uniformName);
  70307. }
  70308. };
  70309. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70310. if (this._samplers.indexOf(name) === -1) {
  70311. this._samplers.push(name);
  70312. }
  70313. this._textures[name] = texture;
  70314. return this;
  70315. };
  70316. ProceduralTexture.prototype.setFloat = function (name, value) {
  70317. this._checkUniform(name);
  70318. this._floats[name] = value;
  70319. return this;
  70320. };
  70321. ProceduralTexture.prototype.setFloats = function (name, value) {
  70322. this._checkUniform(name);
  70323. this._floatsArrays[name] = value;
  70324. return this;
  70325. };
  70326. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70327. this._checkUniform(name);
  70328. this._colors3[name] = value;
  70329. return this;
  70330. };
  70331. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70332. this._checkUniform(name);
  70333. this._colors4[name] = value;
  70334. return this;
  70335. };
  70336. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70337. this._checkUniform(name);
  70338. this._vectors2[name] = value;
  70339. return this;
  70340. };
  70341. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70342. this._checkUniform(name);
  70343. this._vectors3[name] = value;
  70344. return this;
  70345. };
  70346. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70347. this._checkUniform(name);
  70348. this._matrices[name] = value;
  70349. return this;
  70350. };
  70351. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70352. var scene = this.getScene();
  70353. if (!scene) {
  70354. return;
  70355. }
  70356. var engine = this._engine;
  70357. // Render
  70358. engine.enableEffect(this._effect);
  70359. engine.setState(false);
  70360. // Texture
  70361. for (var name in this._textures) {
  70362. this._effect.setTexture(name, this._textures[name]);
  70363. }
  70364. // Float
  70365. for (name in this._floats) {
  70366. this._effect.setFloat(name, this._floats[name]);
  70367. }
  70368. // Floats
  70369. for (name in this._floatsArrays) {
  70370. this._effect.setArray(name, this._floatsArrays[name]);
  70371. }
  70372. // Color3
  70373. for (name in this._colors3) {
  70374. this._effect.setColor3(name, this._colors3[name]);
  70375. }
  70376. // Color4
  70377. for (name in this._colors4) {
  70378. var color = this._colors4[name];
  70379. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70380. }
  70381. // Vector2
  70382. for (name in this._vectors2) {
  70383. this._effect.setVector2(name, this._vectors2[name]);
  70384. }
  70385. // Vector3
  70386. for (name in this._vectors3) {
  70387. this._effect.setVector3(name, this._vectors3[name]);
  70388. }
  70389. // Matrix
  70390. for (name in this._matrices) {
  70391. this._effect.setMatrix(name, this._matrices[name]);
  70392. }
  70393. if (!this._texture) {
  70394. return;
  70395. }
  70396. if (this.isCube) {
  70397. for (var face = 0; face < 6; face++) {
  70398. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70399. // VBOs
  70400. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70401. this._effect.setFloat("face", face);
  70402. // Clear
  70403. engine.clear(scene.clearColor, true, true, true);
  70404. // Draw order
  70405. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70406. // Mipmaps
  70407. if (face === 5) {
  70408. engine.generateMipMapsForCubemap(this._texture);
  70409. }
  70410. }
  70411. }
  70412. else {
  70413. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70414. // VBOs
  70415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70416. // Clear
  70417. engine.clear(scene.clearColor, true, true, true);
  70418. // Draw order
  70419. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70420. }
  70421. // Unbind
  70422. engine.unBindFramebuffer(this._texture, this.isCube);
  70423. if (this.onGenerated) {
  70424. this.onGenerated();
  70425. }
  70426. };
  70427. ProceduralTexture.prototype.clone = function () {
  70428. var textureSize = this.getSize();
  70429. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70430. // Base texture
  70431. newTexture.hasAlpha = this.hasAlpha;
  70432. newTexture.level = this.level;
  70433. // RenderTarget Texture
  70434. newTexture.coordinatesMode = this.coordinatesMode;
  70435. return newTexture;
  70436. };
  70437. ProceduralTexture.prototype.dispose = function () {
  70438. var scene = this.getScene();
  70439. if (!scene) {
  70440. return;
  70441. }
  70442. var index = scene.proceduralTextures.indexOf(this);
  70443. if (index >= 0) {
  70444. scene.proceduralTextures.splice(index, 1);
  70445. }
  70446. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70447. if (vertexBuffer) {
  70448. vertexBuffer.dispose();
  70449. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70450. }
  70451. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70452. this._indexBuffer = null;
  70453. }
  70454. _super.prototype.dispose.call(this);
  70455. };
  70456. __decorate([
  70457. BABYLON.serialize()
  70458. ], ProceduralTexture.prototype, "_size", void 0);
  70459. __decorate([
  70460. BABYLON.serialize()
  70461. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70462. __decorate([
  70463. BABYLON.serialize()
  70464. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70465. __decorate([
  70466. BABYLON.serialize()
  70467. ], ProceduralTexture.prototype, "refreshRate", null);
  70468. return ProceduralTexture;
  70469. }(BABYLON.Texture));
  70470. BABYLON.ProceduralTexture = ProceduralTexture;
  70471. })(BABYLON || (BABYLON = {}));
  70472. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70473. var BABYLON;
  70474. (function (BABYLON) {
  70475. var CustomProceduralTexture = /** @class */ (function (_super) {
  70476. __extends(CustomProceduralTexture, _super);
  70477. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70478. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70479. _this._animate = true;
  70480. _this._time = 0;
  70481. _this._texturePath = texturePath;
  70482. //Try to load json
  70483. _this.loadJson(texturePath);
  70484. _this.refreshRate = 1;
  70485. return _this;
  70486. }
  70487. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70488. var _this = this;
  70489. var noConfigFile = function () {
  70490. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70491. try {
  70492. _this.setFragment(_this._texturePath);
  70493. }
  70494. catch (ex) {
  70495. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70496. }
  70497. };
  70498. var configFileUrl = jsonUrl + "/config.json";
  70499. var xhr = new XMLHttpRequest();
  70500. xhr.open("GET", configFileUrl, true);
  70501. xhr.addEventListener("load", function () {
  70502. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70503. try {
  70504. _this._config = JSON.parse(xhr.response);
  70505. _this.updateShaderUniforms();
  70506. _this.updateTextures();
  70507. _this.setFragment(_this._texturePath + "/custom");
  70508. _this._animate = _this._config.animate;
  70509. _this.refreshRate = _this._config.refreshrate;
  70510. }
  70511. catch (ex) {
  70512. noConfigFile();
  70513. }
  70514. }
  70515. else {
  70516. noConfigFile();
  70517. }
  70518. }, false);
  70519. xhr.addEventListener("error", function () {
  70520. noConfigFile();
  70521. }, false);
  70522. try {
  70523. xhr.send();
  70524. }
  70525. catch (ex) {
  70526. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70527. }
  70528. };
  70529. CustomProceduralTexture.prototype.isReady = function () {
  70530. if (!_super.prototype.isReady.call(this)) {
  70531. return false;
  70532. }
  70533. for (var name in this._textures) {
  70534. var texture = this._textures[name];
  70535. if (!texture.isReady()) {
  70536. return false;
  70537. }
  70538. }
  70539. return true;
  70540. };
  70541. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70542. var scene = this.getScene();
  70543. if (this._animate && scene) {
  70544. this._time += scene.getAnimationRatio() * 0.03;
  70545. this.updateShaderUniforms();
  70546. }
  70547. _super.prototype.render.call(this, useCameraPostProcess);
  70548. };
  70549. CustomProceduralTexture.prototype.updateTextures = function () {
  70550. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70551. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70552. }
  70553. };
  70554. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70555. if (this._config) {
  70556. for (var j = 0; j < this._config.uniforms.length; j++) {
  70557. var uniform = this._config.uniforms[j];
  70558. switch (uniform.type) {
  70559. case "float":
  70560. this.setFloat(uniform.name, uniform.value);
  70561. break;
  70562. case "color3":
  70563. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70564. break;
  70565. case "color4":
  70566. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70567. break;
  70568. case "vector2":
  70569. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70570. break;
  70571. case "vector3":
  70572. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70573. break;
  70574. }
  70575. }
  70576. }
  70577. this.setFloat("time", this._time);
  70578. };
  70579. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70580. get: function () {
  70581. return this._animate;
  70582. },
  70583. set: function (value) {
  70584. this._animate = value;
  70585. },
  70586. enumerable: true,
  70587. configurable: true
  70588. });
  70589. return CustomProceduralTexture;
  70590. }(BABYLON.ProceduralTexture));
  70591. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70592. })(BABYLON || (BABYLON = {}));
  70593. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70594. var BABYLON;
  70595. (function (BABYLON) {
  70596. var FreeCameraGamepadInput = /** @class */ (function () {
  70597. function FreeCameraGamepadInput() {
  70598. this.gamepadAngularSensibility = 200;
  70599. this.gamepadMoveSensibility = 40;
  70600. // private members
  70601. this._cameraTransform = BABYLON.Matrix.Identity();
  70602. this._deltaTransform = BABYLON.Vector3.Zero();
  70603. this._vector3 = BABYLON.Vector3.Zero();
  70604. this._vector2 = BABYLON.Vector2.Zero();
  70605. }
  70606. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70607. var _this = this;
  70608. var manager = this.camera.getScene().gamepadManager;
  70609. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70610. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70611. // prioritize XBOX gamepads.
  70612. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70613. _this.gamepad = gamepad;
  70614. }
  70615. }
  70616. });
  70617. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70618. if (_this.gamepad === gamepad) {
  70619. _this.gamepad = null;
  70620. }
  70621. });
  70622. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70623. };
  70624. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70625. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70626. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70627. this.gamepad = null;
  70628. };
  70629. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70630. if (this.gamepad && this.gamepad.leftStick) {
  70631. var camera = this.camera;
  70632. var LSValues = this.gamepad.leftStick;
  70633. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70634. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70635. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70636. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70637. var RSValues = this.gamepad.rightStick;
  70638. if (RSValues) {
  70639. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70640. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70641. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70642. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70643. }
  70644. else {
  70645. RSValues = { x: 0, y: 0 };
  70646. }
  70647. if (!camera.rotationQuaternion) {
  70648. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70649. }
  70650. else {
  70651. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70652. }
  70653. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70654. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70655. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70656. camera.cameraDirection.addInPlace(this._deltaTransform);
  70657. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70658. camera.cameraRotation.addInPlace(this._vector2);
  70659. }
  70660. };
  70661. FreeCameraGamepadInput.prototype.getClassName = function () {
  70662. return "FreeCameraGamepadInput";
  70663. };
  70664. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70665. return "gamepad";
  70666. };
  70667. __decorate([
  70668. BABYLON.serialize()
  70669. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70670. __decorate([
  70671. BABYLON.serialize()
  70672. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70673. return FreeCameraGamepadInput;
  70674. }());
  70675. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70676. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70677. })(BABYLON || (BABYLON = {}));
  70678. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70679. var BABYLON;
  70680. (function (BABYLON) {
  70681. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70682. function ArcRotateCameraGamepadInput() {
  70683. this.gamepadRotationSensibility = 80;
  70684. this.gamepadMoveSensibility = 40;
  70685. }
  70686. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70687. var _this = this;
  70688. var manager = this.camera.getScene().gamepadManager;
  70689. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70690. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70691. // prioritize XBOX gamepads.
  70692. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70693. _this.gamepad = gamepad;
  70694. }
  70695. }
  70696. });
  70697. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70698. if (_this.gamepad === gamepad) {
  70699. _this.gamepad = null;
  70700. }
  70701. });
  70702. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70703. };
  70704. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70705. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70706. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70707. this.gamepad = null;
  70708. };
  70709. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70710. if (this.gamepad) {
  70711. var camera = this.camera;
  70712. var RSValues = this.gamepad.rightStick;
  70713. if (RSValues) {
  70714. if (RSValues.x != 0) {
  70715. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70716. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70717. camera.inertialAlphaOffset += normalizedRX;
  70718. }
  70719. }
  70720. if (RSValues.y != 0) {
  70721. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70722. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70723. camera.inertialBetaOffset += normalizedRY;
  70724. }
  70725. }
  70726. }
  70727. var LSValues = this.gamepad.leftStick;
  70728. if (LSValues && LSValues.y != 0) {
  70729. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70730. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70731. this.camera.inertialRadiusOffset -= normalizedLY;
  70732. }
  70733. }
  70734. }
  70735. };
  70736. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70737. return "ArcRotateCameraGamepadInput";
  70738. };
  70739. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70740. return "gamepad";
  70741. };
  70742. __decorate([
  70743. BABYLON.serialize()
  70744. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70745. __decorate([
  70746. BABYLON.serialize()
  70747. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70748. return ArcRotateCameraGamepadInput;
  70749. }());
  70750. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70751. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70752. })(BABYLON || (BABYLON = {}));
  70753. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70754. var BABYLON;
  70755. (function (BABYLON) {
  70756. var GamepadManager = /** @class */ (function () {
  70757. function GamepadManager(_scene) {
  70758. var _this = this;
  70759. this._scene = _scene;
  70760. this._babylonGamepads = [];
  70761. this._oneGamepadConnected = false;
  70762. this._isMonitoring = false;
  70763. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70764. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70765. this._gamepadEventSupported = false;
  70766. }
  70767. else {
  70768. this._gamepadEventSupported = 'GamepadEvent' in window;
  70769. this._gamepadSupport = (navigator.getGamepads ||
  70770. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70771. }
  70772. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70773. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70774. for (var i in _this._babylonGamepads) {
  70775. var gamepad = _this._babylonGamepads[i];
  70776. if (gamepad && gamepad._isConnected) {
  70777. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70778. }
  70779. }
  70780. });
  70781. this._onGamepadConnectedEvent = function (evt) {
  70782. var gamepad = evt.gamepad;
  70783. if (gamepad.index in _this._babylonGamepads) {
  70784. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70785. return;
  70786. }
  70787. }
  70788. var newGamepad;
  70789. if (_this._babylonGamepads[gamepad.index]) {
  70790. newGamepad = _this._babylonGamepads[gamepad.index];
  70791. newGamepad.browserGamepad = gamepad;
  70792. newGamepad._isConnected = true;
  70793. }
  70794. else {
  70795. newGamepad = _this._addNewGamepad(gamepad);
  70796. }
  70797. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70798. _this._startMonitoringGamepads();
  70799. };
  70800. this._onGamepadDisconnectedEvent = function (evt) {
  70801. var gamepad = evt.gamepad;
  70802. // Remove the gamepad from the list of gamepads to monitor.
  70803. for (var i in _this._babylonGamepads) {
  70804. if (_this._babylonGamepads[i].index === gamepad.index) {
  70805. var disconnectedGamepad = _this._babylonGamepads[i];
  70806. disconnectedGamepad._isConnected = false;
  70807. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70808. break;
  70809. }
  70810. }
  70811. };
  70812. if (this._gamepadSupport) {
  70813. //first add already-connected gamepads
  70814. this._updateGamepadObjects();
  70815. if (this._babylonGamepads.length) {
  70816. this._startMonitoringGamepads();
  70817. }
  70818. // Checking if the gamepad connected event is supported (like in Firefox)
  70819. if (this._gamepadEventSupported) {
  70820. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70821. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70822. }
  70823. else {
  70824. this._startMonitoringGamepads();
  70825. }
  70826. }
  70827. }
  70828. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70829. get: function () {
  70830. return this._babylonGamepads;
  70831. },
  70832. enumerable: true,
  70833. configurable: true
  70834. });
  70835. GamepadManager.prototype.getGamepadByType = function (type) {
  70836. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70837. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70838. var gamepad = _a[_i];
  70839. if (gamepad && gamepad.type === type) {
  70840. return gamepad;
  70841. }
  70842. }
  70843. return null;
  70844. };
  70845. GamepadManager.prototype.dispose = function () {
  70846. if (this._gamepadEventSupported) {
  70847. if (this._onGamepadConnectedEvent) {
  70848. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70849. }
  70850. if (this._onGamepadDisconnectedEvent) {
  70851. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70852. }
  70853. this._onGamepadConnectedEvent = null;
  70854. this._onGamepadDisconnectedEvent = null;
  70855. }
  70856. this._babylonGamepads.forEach(function (gamepad) {
  70857. gamepad.dispose();
  70858. });
  70859. this.onGamepadConnectedObservable.clear();
  70860. this.onGamepadDisconnectedObservable.clear();
  70861. this._oneGamepadConnected = false;
  70862. this._stopMonitoringGamepads();
  70863. this._babylonGamepads = [];
  70864. };
  70865. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70866. if (!this._oneGamepadConnected) {
  70867. this._oneGamepadConnected = true;
  70868. }
  70869. var newGamepad;
  70870. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70871. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70872. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70873. }
  70874. // if pose is supported, use the (WebVR) pose enabled controller
  70875. else if (gamepad.pose) {
  70876. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70877. }
  70878. else {
  70879. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70880. }
  70881. this._babylonGamepads[newGamepad.index] = newGamepad;
  70882. return newGamepad;
  70883. };
  70884. GamepadManager.prototype._startMonitoringGamepads = function () {
  70885. if (!this._isMonitoring) {
  70886. this._isMonitoring = true;
  70887. //back-comp
  70888. if (!this._scene) {
  70889. this._checkGamepadsStatus();
  70890. }
  70891. }
  70892. };
  70893. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70894. this._isMonitoring = false;
  70895. };
  70896. GamepadManager.prototype._checkGamepadsStatus = function () {
  70897. var _this = this;
  70898. // Hack to be compatible Chrome
  70899. this._updateGamepadObjects();
  70900. for (var i in this._babylonGamepads) {
  70901. var gamepad = this._babylonGamepads[i];
  70902. if (!gamepad || !gamepad.isConnected) {
  70903. continue;
  70904. }
  70905. gamepad.update();
  70906. }
  70907. if (this._isMonitoring && !this._scene) {
  70908. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70909. }
  70910. };
  70911. // This function is called only on Chrome, which does not properly support
  70912. // connection/disconnection events and forces you to recopy again the gamepad object
  70913. GamepadManager.prototype._updateGamepadObjects = function () {
  70914. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70915. for (var i = 0; i < gamepads.length; i++) {
  70916. var gamepad = gamepads[i];
  70917. if (gamepad) {
  70918. if (!this._babylonGamepads[gamepad.index]) {
  70919. var newGamepad = this._addNewGamepad(gamepad);
  70920. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70921. }
  70922. else {
  70923. // Forced to copy again this object for Chrome for unknown reason
  70924. this._babylonGamepads[i].browserGamepad = gamepad;
  70925. if (!this._babylonGamepads[i].isConnected) {
  70926. this._babylonGamepads[i]._isConnected = true;
  70927. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70928. }
  70929. }
  70930. }
  70931. }
  70932. };
  70933. return GamepadManager;
  70934. }());
  70935. BABYLON.GamepadManager = GamepadManager;
  70936. })(BABYLON || (BABYLON = {}));
  70937. //# sourceMappingURL=babylon.gamepadManager.js.map
  70938. var BABYLON;
  70939. (function (BABYLON) {
  70940. var StickValues = /** @class */ (function () {
  70941. function StickValues(x, y) {
  70942. this.x = x;
  70943. this.y = y;
  70944. }
  70945. return StickValues;
  70946. }());
  70947. BABYLON.StickValues = StickValues;
  70948. var Gamepad = /** @class */ (function () {
  70949. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70950. if (leftStickX === void 0) { leftStickX = 0; }
  70951. if (leftStickY === void 0) { leftStickY = 1; }
  70952. if (rightStickX === void 0) { rightStickX = 2; }
  70953. if (rightStickY === void 0) { rightStickY = 3; }
  70954. this.id = id;
  70955. this.index = index;
  70956. this.browserGamepad = browserGamepad;
  70957. this._isConnected = true;
  70958. this._invertLeftStickY = false;
  70959. this.type = Gamepad.GAMEPAD;
  70960. this._leftStickAxisX = leftStickX;
  70961. this._leftStickAxisY = leftStickY;
  70962. this._rightStickAxisX = rightStickX;
  70963. this._rightStickAxisY = rightStickY;
  70964. if (this.browserGamepad.axes.length >= 2) {
  70965. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70966. }
  70967. if (this.browserGamepad.axes.length >= 4) {
  70968. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70969. }
  70970. }
  70971. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70972. get: function () {
  70973. return this._isConnected;
  70974. },
  70975. enumerable: true,
  70976. configurable: true
  70977. });
  70978. Gamepad.prototype.onleftstickchanged = function (callback) {
  70979. this._onleftstickchanged = callback;
  70980. };
  70981. Gamepad.prototype.onrightstickchanged = function (callback) {
  70982. this._onrightstickchanged = callback;
  70983. };
  70984. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70985. get: function () {
  70986. return this._leftStick;
  70987. },
  70988. set: function (newValues) {
  70989. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70990. this._onleftstickchanged(newValues);
  70991. }
  70992. this._leftStick = newValues;
  70993. },
  70994. enumerable: true,
  70995. configurable: true
  70996. });
  70997. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70998. get: function () {
  70999. return this._rightStick;
  71000. },
  71001. set: function (newValues) {
  71002. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71003. this._onrightstickchanged(newValues);
  71004. }
  71005. this._rightStick = newValues;
  71006. },
  71007. enumerable: true,
  71008. configurable: true
  71009. });
  71010. Gamepad.prototype.update = function () {
  71011. if (this._leftStick) {
  71012. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71013. if (this._invertLeftStickY) {
  71014. this.leftStick.y *= -1;
  71015. }
  71016. }
  71017. if (this._rightStick) {
  71018. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71019. }
  71020. };
  71021. Gamepad.prototype.dispose = function () {
  71022. };
  71023. Gamepad.GAMEPAD = 0;
  71024. Gamepad.GENERIC = 1;
  71025. Gamepad.XBOX = 2;
  71026. Gamepad.POSE_ENABLED = 3;
  71027. return Gamepad;
  71028. }());
  71029. BABYLON.Gamepad = Gamepad;
  71030. var GenericPad = /** @class */ (function (_super) {
  71031. __extends(GenericPad, _super);
  71032. function GenericPad(id, index, browserGamepad) {
  71033. var _this = _super.call(this, id, index, browserGamepad) || this;
  71034. _this.onButtonDownObservable = new BABYLON.Observable();
  71035. _this.onButtonUpObservable = new BABYLON.Observable();
  71036. _this.type = Gamepad.GENERIC;
  71037. _this._buttons = new Array(browserGamepad.buttons.length);
  71038. return _this;
  71039. }
  71040. GenericPad.prototype.onbuttondown = function (callback) {
  71041. this._onbuttondown = callback;
  71042. };
  71043. GenericPad.prototype.onbuttonup = function (callback) {
  71044. this._onbuttonup = callback;
  71045. };
  71046. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71047. if (newValue !== currentValue) {
  71048. if (newValue === 1) {
  71049. if (this._onbuttondown) {
  71050. this._onbuttondown(buttonIndex);
  71051. }
  71052. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71053. }
  71054. if (newValue === 0) {
  71055. if (this._onbuttonup) {
  71056. this._onbuttonup(buttonIndex);
  71057. }
  71058. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71059. }
  71060. }
  71061. return newValue;
  71062. };
  71063. GenericPad.prototype.update = function () {
  71064. _super.prototype.update.call(this);
  71065. for (var index = 0; index < this._buttons.length; index++) {
  71066. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71067. }
  71068. };
  71069. GenericPad.prototype.dispose = function () {
  71070. _super.prototype.dispose.call(this);
  71071. this.onButtonDownObservable.clear();
  71072. this.onButtonUpObservable.clear();
  71073. };
  71074. return GenericPad;
  71075. }(Gamepad));
  71076. BABYLON.GenericPad = GenericPad;
  71077. })(BABYLON || (BABYLON = {}));
  71078. //# sourceMappingURL=babylon.gamepad.js.map
  71079. var BABYLON;
  71080. (function (BABYLON) {
  71081. /**
  71082. * Defines supported buttons for XBox360 compatible gamepads
  71083. */
  71084. var Xbox360Button;
  71085. (function (Xbox360Button) {
  71086. /** A */
  71087. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71088. /** B */
  71089. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71090. /** X */
  71091. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71092. /** Y */
  71093. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71094. /** Start */
  71095. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71096. /** Back */
  71097. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71098. /** Left button */
  71099. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71100. /** Right button */
  71101. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71102. /** Left stick */
  71103. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71104. /** Right stick */
  71105. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71106. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71107. /** Defines values for XBox360 DPad */
  71108. var Xbox360Dpad;
  71109. (function (Xbox360Dpad) {
  71110. /** Up */
  71111. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71112. /** Down */
  71113. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71114. /** Left */
  71115. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71116. /** Right */
  71117. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71118. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71119. /**
  71120. * Defines a XBox360 gamepad
  71121. */
  71122. var Xbox360Pad = /** @class */ (function (_super) {
  71123. __extends(Xbox360Pad, _super);
  71124. /**
  71125. * Creates a new XBox360 gamepad object
  71126. * @param id defines the id of this gamepad
  71127. * @param index defines its index
  71128. * @param gamepad defines the internal HTML gamepad object
  71129. * @param xboxOne defines if it is a XBox One gamepad
  71130. */
  71131. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71132. if (xboxOne === void 0) { xboxOne = false; }
  71133. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71134. _this._leftTrigger = 0;
  71135. _this._rightTrigger = 0;
  71136. /** Observable raised when a button is pressed */
  71137. _this.onButtonDownObservable = new BABYLON.Observable();
  71138. /** Observable raised when a button is released */
  71139. _this.onButtonUpObservable = new BABYLON.Observable();
  71140. /** Observable raised when a pad is pressed */
  71141. _this.onPadDownObservable = new BABYLON.Observable();
  71142. /** Observable raised when a pad is released */
  71143. _this.onPadUpObservable = new BABYLON.Observable();
  71144. _this._buttonA = 0;
  71145. _this._buttonB = 0;
  71146. _this._buttonX = 0;
  71147. _this._buttonY = 0;
  71148. _this._buttonBack = 0;
  71149. _this._buttonStart = 0;
  71150. _this._buttonLB = 0;
  71151. _this._buttonRB = 0;
  71152. _this._buttonLeftStick = 0;
  71153. _this._buttonRightStick = 0;
  71154. _this._dPadUp = 0;
  71155. _this._dPadDown = 0;
  71156. _this._dPadLeft = 0;
  71157. _this._dPadRight = 0;
  71158. _this._isXboxOnePad = false;
  71159. _this.type = BABYLON.Gamepad.XBOX;
  71160. _this._isXboxOnePad = xboxOne;
  71161. return _this;
  71162. }
  71163. /**
  71164. * Defines the callback to call when left trigger is pressed
  71165. * @param callback defines the callback to use
  71166. */
  71167. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71168. this._onlefttriggerchanged = callback;
  71169. };
  71170. /**
  71171. * Defines the callback to call when right trigger is pressed
  71172. * @param callback defines the callback to use
  71173. */
  71174. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71175. this._onrighttriggerchanged = callback;
  71176. };
  71177. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71178. /**
  71179. * Gets or sets left trigger value
  71180. */
  71181. get: function () {
  71182. return this._leftTrigger;
  71183. },
  71184. set: function (newValue) {
  71185. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71186. this._onlefttriggerchanged(newValue);
  71187. }
  71188. this._leftTrigger = newValue;
  71189. },
  71190. enumerable: true,
  71191. configurable: true
  71192. });
  71193. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71194. /**
  71195. * Gets or sets right trigger value
  71196. */
  71197. get: function () {
  71198. return this._rightTrigger;
  71199. },
  71200. set: function (newValue) {
  71201. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71202. this._onrighttriggerchanged(newValue);
  71203. }
  71204. this._rightTrigger = newValue;
  71205. },
  71206. enumerable: true,
  71207. configurable: true
  71208. });
  71209. /**
  71210. * Defines the callback to call when a button is pressed
  71211. * @param callback defines the callback to use
  71212. */
  71213. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71214. this._onbuttondown = callback;
  71215. };
  71216. /**
  71217. * Defines the callback to call when a button is released
  71218. * @param callback defines the callback to use
  71219. */
  71220. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71221. this._onbuttonup = callback;
  71222. };
  71223. /**
  71224. * Defines the callback to call when a pad is pressed
  71225. * @param callback defines the callback to use
  71226. */
  71227. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71228. this._ondpaddown = callback;
  71229. };
  71230. /**
  71231. * Defines the callback to call when a pad is released
  71232. * @param callback defines the callback to use
  71233. */
  71234. Xbox360Pad.prototype.ondpadup = function (callback) {
  71235. this._ondpadup = callback;
  71236. };
  71237. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71238. if (newValue !== currentValue) {
  71239. if (newValue === 1) {
  71240. if (this._onbuttondown) {
  71241. this._onbuttondown(buttonType);
  71242. }
  71243. this.onButtonDownObservable.notifyObservers(buttonType);
  71244. }
  71245. if (newValue === 0) {
  71246. if (this._onbuttonup) {
  71247. this._onbuttonup(buttonType);
  71248. }
  71249. this.onButtonUpObservable.notifyObservers(buttonType);
  71250. }
  71251. }
  71252. return newValue;
  71253. };
  71254. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71255. if (newValue !== currentValue) {
  71256. if (newValue === 1) {
  71257. if (this._ondpaddown) {
  71258. this._ondpaddown(buttonType);
  71259. }
  71260. this.onPadDownObservable.notifyObservers(buttonType);
  71261. }
  71262. if (newValue === 0) {
  71263. if (this._ondpadup) {
  71264. this._ondpadup(buttonType);
  71265. }
  71266. this.onPadUpObservable.notifyObservers(buttonType);
  71267. }
  71268. }
  71269. return newValue;
  71270. };
  71271. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71272. /** Gets or sets value of A button */
  71273. get: function () {
  71274. return this._buttonA;
  71275. },
  71276. set: function (value) {
  71277. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71278. },
  71279. enumerable: true,
  71280. configurable: true
  71281. });
  71282. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71283. /** Gets or sets value of B button */
  71284. get: function () {
  71285. return this._buttonB;
  71286. },
  71287. set: function (value) {
  71288. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71289. },
  71290. enumerable: true,
  71291. configurable: true
  71292. });
  71293. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71294. /** Gets or sets value of X button */
  71295. get: function () {
  71296. return this._buttonX;
  71297. },
  71298. set: function (value) {
  71299. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71300. },
  71301. enumerable: true,
  71302. configurable: true
  71303. });
  71304. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71305. /** Gets or sets value of Y button */
  71306. get: function () {
  71307. return this._buttonY;
  71308. },
  71309. set: function (value) {
  71310. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71311. },
  71312. enumerable: true,
  71313. configurable: true
  71314. });
  71315. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71316. /** Gets or sets value of Start button */
  71317. get: function () {
  71318. return this._buttonStart;
  71319. },
  71320. set: function (value) {
  71321. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71322. },
  71323. enumerable: true,
  71324. configurable: true
  71325. });
  71326. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71327. /** Gets or sets value of Back button */
  71328. get: function () {
  71329. return this._buttonBack;
  71330. },
  71331. set: function (value) {
  71332. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71333. },
  71334. enumerable: true,
  71335. configurable: true
  71336. });
  71337. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71338. /** Gets or sets value of Left button */
  71339. get: function () {
  71340. return this._buttonLB;
  71341. },
  71342. set: function (value) {
  71343. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71344. },
  71345. enumerable: true,
  71346. configurable: true
  71347. });
  71348. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71349. /** Gets or sets value of Right button */
  71350. get: function () {
  71351. return this._buttonRB;
  71352. },
  71353. set: function (value) {
  71354. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71355. },
  71356. enumerable: true,
  71357. configurable: true
  71358. });
  71359. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71360. /** Gets or sets value of left stick */
  71361. get: function () {
  71362. return this._buttonLeftStick;
  71363. },
  71364. set: function (value) {
  71365. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71371. /** Gets or sets value of right stick */
  71372. get: function () {
  71373. return this._buttonRightStick;
  71374. },
  71375. set: function (value) {
  71376. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71377. },
  71378. enumerable: true,
  71379. configurable: true
  71380. });
  71381. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71382. /** Gets or sets value of DPad up */
  71383. get: function () {
  71384. return this._dPadUp;
  71385. },
  71386. set: function (value) {
  71387. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71388. },
  71389. enumerable: true,
  71390. configurable: true
  71391. });
  71392. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71393. /** Gets or sets value of DPad down */
  71394. get: function () {
  71395. return this._dPadDown;
  71396. },
  71397. set: function (value) {
  71398. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71399. },
  71400. enumerable: true,
  71401. configurable: true
  71402. });
  71403. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71404. /** Gets or sets value of DPad left */
  71405. get: function () {
  71406. return this._dPadLeft;
  71407. },
  71408. set: function (value) {
  71409. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71410. },
  71411. enumerable: true,
  71412. configurable: true
  71413. });
  71414. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71415. /** Gets or sets value of DPad right */
  71416. get: function () {
  71417. return this._dPadRight;
  71418. },
  71419. set: function (value) {
  71420. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71421. },
  71422. enumerable: true,
  71423. configurable: true
  71424. });
  71425. /**
  71426. * Force the gamepad to synchronize with device values
  71427. */
  71428. Xbox360Pad.prototype.update = function () {
  71429. _super.prototype.update.call(this);
  71430. if (this._isXboxOnePad) {
  71431. this.buttonA = this.browserGamepad.buttons[0].value;
  71432. this.buttonB = this.browserGamepad.buttons[1].value;
  71433. this.buttonX = this.browserGamepad.buttons[2].value;
  71434. this.buttonY = this.browserGamepad.buttons[3].value;
  71435. this.buttonLB = this.browserGamepad.buttons[4].value;
  71436. this.buttonRB = this.browserGamepad.buttons[5].value;
  71437. this.leftTrigger = this.browserGamepad.axes[2];
  71438. this.rightTrigger = this.browserGamepad.axes[5];
  71439. this.buttonBack = this.browserGamepad.buttons[9].value;
  71440. this.buttonStart = this.browserGamepad.buttons[8].value;
  71441. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71442. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71443. this.dPadUp = this.browserGamepad.buttons[11].value;
  71444. this.dPadDown = this.browserGamepad.buttons[12].value;
  71445. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71446. this.dPadRight = this.browserGamepad.buttons[14].value;
  71447. }
  71448. else {
  71449. this.buttonA = this.browserGamepad.buttons[0].value;
  71450. this.buttonB = this.browserGamepad.buttons[1].value;
  71451. this.buttonX = this.browserGamepad.buttons[2].value;
  71452. this.buttonY = this.browserGamepad.buttons[3].value;
  71453. this.buttonLB = this.browserGamepad.buttons[4].value;
  71454. this.buttonRB = this.browserGamepad.buttons[5].value;
  71455. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71456. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71457. this.buttonBack = this.browserGamepad.buttons[8].value;
  71458. this.buttonStart = this.browserGamepad.buttons[9].value;
  71459. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71460. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71461. this.dPadUp = this.browserGamepad.buttons[12].value;
  71462. this.dPadDown = this.browserGamepad.buttons[13].value;
  71463. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71464. this.dPadRight = this.browserGamepad.buttons[15].value;
  71465. }
  71466. };
  71467. Xbox360Pad.prototype.dispose = function () {
  71468. _super.prototype.dispose.call(this);
  71469. this.onButtonDownObservable.clear();
  71470. this.onButtonUpObservable.clear();
  71471. this.onPadDownObservable.clear();
  71472. this.onPadUpObservable.clear();
  71473. };
  71474. return Xbox360Pad;
  71475. }(BABYLON.Gamepad));
  71476. BABYLON.Xbox360Pad = Xbox360Pad;
  71477. })(BABYLON || (BABYLON = {}));
  71478. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71479. var BABYLON;
  71480. (function (BABYLON) {
  71481. /**
  71482. * Defines the types of pose enabled controllers that are supported
  71483. */
  71484. var PoseEnabledControllerType;
  71485. (function (PoseEnabledControllerType) {
  71486. /**
  71487. * HTC Vive
  71488. */
  71489. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71490. /**
  71491. * Oculus Rift
  71492. */
  71493. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71494. /**
  71495. * Windows mixed reality
  71496. */
  71497. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71498. /**
  71499. * Samsung gear VR
  71500. */
  71501. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71502. /**
  71503. * Google Daydream
  71504. */
  71505. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71506. /**
  71507. * Generic
  71508. */
  71509. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71510. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71511. /**
  71512. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71513. */
  71514. var PoseEnabledControllerHelper = /** @class */ (function () {
  71515. function PoseEnabledControllerHelper() {
  71516. }
  71517. /**
  71518. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71519. * @param vrGamepad the gamepad to initialized
  71520. * @returns a vr controller of the type the gamepad identified as
  71521. */
  71522. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71523. // Oculus Touch
  71524. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71525. return new BABYLON.OculusTouchController(vrGamepad);
  71526. }
  71527. // Windows Mixed Reality controllers
  71528. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71529. return new BABYLON.WindowsMotionController(vrGamepad);
  71530. }
  71531. // HTC Vive
  71532. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71533. return new BABYLON.ViveController(vrGamepad);
  71534. }
  71535. // Samsung/Oculus Gear VR or Oculus Go
  71536. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71537. return new BABYLON.GearVRController(vrGamepad);
  71538. }
  71539. // Google Daydream
  71540. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71541. return new BABYLON.DaydreamController(vrGamepad);
  71542. }
  71543. // Generic
  71544. else {
  71545. return new BABYLON.GenericController(vrGamepad);
  71546. }
  71547. };
  71548. return PoseEnabledControllerHelper;
  71549. }());
  71550. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71551. /**
  71552. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71553. */
  71554. var PoseEnabledController = /** @class */ (function (_super) {
  71555. __extends(PoseEnabledController, _super);
  71556. /**
  71557. * Creates a new PoseEnabledController from a gamepad
  71558. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71559. */
  71560. function PoseEnabledController(browserGamepad) {
  71561. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71562. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71563. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71564. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71565. /**
  71566. * The device position in babylon space
  71567. */
  71568. _this.devicePosition = BABYLON.Vector3.Zero();
  71569. /**
  71570. * The device rotation in babylon space
  71571. */
  71572. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71573. /**
  71574. * The scale factor of the device in babylon space
  71575. */
  71576. _this.deviceScaleFactor = 1;
  71577. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71578. /**
  71579. * Internal, matrix used to convert room space to babylon space
  71580. */
  71581. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71582. /**
  71583. * Node to be used when casting a ray from the controller
  71584. */
  71585. _this._pointingPoseNode = null;
  71586. _this._workingMatrix = BABYLON.Matrix.Identity();
  71587. /**
  71588. * @hidden
  71589. */
  71590. _this._meshAttachedObservable = new BABYLON.Observable();
  71591. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71592. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71593. _this.position = BABYLON.Vector3.Zero();
  71594. _this.rotationQuaternion = new BABYLON.Quaternion();
  71595. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71596. _this._calculatedRotation = new BABYLON.Quaternion();
  71597. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71598. return _this;
  71599. }
  71600. /**
  71601. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71602. */
  71603. PoseEnabledController.prototype.update = function () {
  71604. _super.prototype.update.call(this);
  71605. this._updatePoseAndMesh();
  71606. };
  71607. /**
  71608. * Updates only the pose device and mesh without doing any button event checking
  71609. */
  71610. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71611. var pose = this.browserGamepad.pose;
  71612. this.updateFromDevice(pose);
  71613. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71614. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71615. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71616. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71617. if (this._mesh) {
  71618. this._mesh.position.copyFrom(this.devicePosition);
  71619. if (this._mesh.rotationQuaternion) {
  71620. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71621. }
  71622. }
  71623. };
  71624. /**
  71625. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71626. * @param poseData raw pose fromthe device
  71627. */
  71628. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71629. if (poseData) {
  71630. this.rawPose = poseData;
  71631. if (poseData.position) {
  71632. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71633. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71634. this._deviceRoomPosition.z *= -1;
  71635. }
  71636. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71637. this._calculatedPosition.addInPlace(this.position);
  71638. }
  71639. var pose = this.rawPose;
  71640. if (poseData.orientation && pose.orientation) {
  71641. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71642. if (this._mesh) {
  71643. if (this._mesh.getScene().useRightHandedSystem) {
  71644. this._deviceRoomRotationQuaternion.z *= -1;
  71645. this._deviceRoomRotationQuaternion.w *= -1;
  71646. }
  71647. else {
  71648. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71649. }
  71650. }
  71651. // if the camera is set, rotate to the camera's rotation
  71652. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71653. }
  71654. }
  71655. };
  71656. /**
  71657. * Attaches a mesh to the controller
  71658. * @param mesh the mesh to be attached
  71659. */
  71660. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71661. if (this._mesh) {
  71662. this._mesh.parent = null;
  71663. }
  71664. this._mesh = mesh;
  71665. if (this._poseControlledCamera) {
  71666. this._mesh.parent = this._poseControlledCamera;
  71667. }
  71668. if (!this._mesh.rotationQuaternion) {
  71669. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71670. }
  71671. // 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
  71672. this._updatePoseAndMesh();
  71673. if (this._pointingPoseNode) {
  71674. var parents = [];
  71675. var obj = this._pointingPoseNode;
  71676. while (obj.parent) {
  71677. parents.push(obj.parent);
  71678. obj = obj.parent;
  71679. }
  71680. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71681. }
  71682. this._meshAttachedObservable.notifyObservers(mesh);
  71683. };
  71684. /**
  71685. * Attaches the controllers mesh to a camera
  71686. * @param camera the camera the mesh should be attached to
  71687. */
  71688. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71689. this._poseControlledCamera = camera;
  71690. if (this._mesh) {
  71691. this._mesh.parent = this._poseControlledCamera;
  71692. }
  71693. };
  71694. /**
  71695. * Disposes of the controller
  71696. */
  71697. PoseEnabledController.prototype.dispose = function () {
  71698. if (this._mesh) {
  71699. this._mesh.dispose();
  71700. }
  71701. this._mesh = null;
  71702. _super.prototype.dispose.call(this);
  71703. };
  71704. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71705. /**
  71706. * The mesh that is attached to the controller
  71707. */
  71708. get: function () {
  71709. return this._mesh;
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. /**
  71715. * Gets the ray of the controller in the direction the controller is pointing
  71716. * @param length the length the resulting ray should be
  71717. * @returns a ray in the direction the controller is pointing
  71718. */
  71719. PoseEnabledController.prototype.getForwardRay = function (length) {
  71720. if (length === void 0) { length = 100; }
  71721. if (!this.mesh) {
  71722. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71723. }
  71724. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71725. var origin = m.getTranslation();
  71726. var forward = new BABYLON.Vector3(0, 0, -1);
  71727. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71728. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71729. return new BABYLON.Ray(origin, direction, length);
  71730. };
  71731. /**
  71732. * Name of the child mesh that can be used to cast a ray from the controller
  71733. */
  71734. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71735. return PoseEnabledController;
  71736. }(BABYLON.Gamepad));
  71737. BABYLON.PoseEnabledController = PoseEnabledController;
  71738. })(BABYLON || (BABYLON = {}));
  71739. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71740. var BABYLON;
  71741. (function (BABYLON) {
  71742. /**
  71743. * Defines the WebVRController object that represents controllers tracked in 3D space
  71744. */
  71745. var WebVRController = /** @class */ (function (_super) {
  71746. __extends(WebVRController, _super);
  71747. /**
  71748. * Creates a new WebVRController from a gamepad
  71749. * @param vrGamepad the gamepad that the WebVRController should be created from
  71750. */
  71751. function WebVRController(vrGamepad) {
  71752. var _this = _super.call(this, vrGamepad) || this;
  71753. // Observables
  71754. /**
  71755. * Fired when the trigger state has changed
  71756. */
  71757. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71758. /**
  71759. * Fired when the main button state has changed
  71760. */
  71761. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71762. /**
  71763. * Fired when the secondary button state has changed
  71764. */
  71765. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71766. /**
  71767. * Fired when the pad state has changed
  71768. */
  71769. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71770. /**
  71771. * Fired when controllers stick values have changed
  71772. */
  71773. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71774. /**
  71775. * X and Y axis corrisponding to the controllers joystick
  71776. */
  71777. _this.pad = { x: 0, y: 0 };
  71778. // avoid GC, store state in a tmp object
  71779. _this._changes = {
  71780. pressChanged: false,
  71781. touchChanged: false,
  71782. valueChanged: false,
  71783. changed: false
  71784. };
  71785. _this._buttons = new Array(vrGamepad.buttons.length);
  71786. _this.hand = vrGamepad.hand;
  71787. return _this;
  71788. }
  71789. /**
  71790. * Fired when a controller button's state has changed
  71791. * @param callback the callback containing the button that was modified
  71792. */
  71793. WebVRController.prototype.onButtonStateChange = function (callback) {
  71794. this._onButtonStateChange = callback;
  71795. };
  71796. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71797. /**
  71798. * The default controller model for the controller
  71799. */
  71800. get: function () {
  71801. return this._defaultModel;
  71802. },
  71803. enumerable: true,
  71804. configurable: true
  71805. });
  71806. /**
  71807. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71808. */
  71809. WebVRController.prototype.update = function () {
  71810. _super.prototype.update.call(this);
  71811. for (var index = 0; index < this._buttons.length; index++) {
  71812. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71813. }
  71814. ;
  71815. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71816. this.pad.x = this.leftStick.x;
  71817. this.pad.y = this.leftStick.y;
  71818. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71819. }
  71820. };
  71821. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71822. if (!newState) {
  71823. newState = {
  71824. pressed: false,
  71825. touched: false,
  71826. value: 0
  71827. };
  71828. }
  71829. if (!currentState) {
  71830. this._buttons[buttonIndex] = {
  71831. pressed: newState.pressed,
  71832. touched: newState.touched,
  71833. value: newState.value
  71834. };
  71835. return;
  71836. }
  71837. this._checkChanges(newState, currentState);
  71838. if (this._changes.changed) {
  71839. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71840. this._handleButtonChange(buttonIndex, newState, this._changes);
  71841. }
  71842. this._buttons[buttonIndex].pressed = newState.pressed;
  71843. this._buttons[buttonIndex].touched = newState.touched;
  71844. // oculus triggers are never 0, thou not touched.
  71845. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71846. };
  71847. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71848. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71849. this._changes.touchChanged = newState.touched !== currentState.touched;
  71850. this._changes.valueChanged = newState.value !== currentState.value;
  71851. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71852. return this._changes;
  71853. };
  71854. /**
  71855. * Disposes of th webVRCOntroller
  71856. */
  71857. WebVRController.prototype.dispose = function () {
  71858. _super.prototype.dispose.call(this);
  71859. this.onTriggerStateChangedObservable.clear();
  71860. this.onMainButtonStateChangedObservable.clear();
  71861. this.onSecondaryButtonStateChangedObservable.clear();
  71862. this.onPadStateChangedObservable.clear();
  71863. this.onPadValuesChangedObservable.clear();
  71864. };
  71865. return WebVRController;
  71866. }(BABYLON.PoseEnabledController));
  71867. BABYLON.WebVRController = WebVRController;
  71868. })(BABYLON || (BABYLON = {}));
  71869. //# sourceMappingURL=babylon.webVRController.js.map
  71870. var BABYLON;
  71871. (function (BABYLON) {
  71872. /**
  71873. * Oculus Touch Controller
  71874. */
  71875. var OculusTouchController = /** @class */ (function (_super) {
  71876. __extends(OculusTouchController, _super);
  71877. /**
  71878. * Creates a new OculusTouchController from a gamepad
  71879. * @param vrGamepad the gamepad that the controller should be created from
  71880. */
  71881. function OculusTouchController(vrGamepad) {
  71882. var _this = _super.call(this, vrGamepad) || this;
  71883. /**
  71884. * Fired when the secondary trigger on this controller is modified
  71885. */
  71886. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71887. /**
  71888. * Fired when the thumb rest on this controller is modified
  71889. */
  71890. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71891. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71892. return _this;
  71893. }
  71894. /**
  71895. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71896. * @param scene scene in which to add meshes
  71897. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71898. */
  71899. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71900. var _this = this;
  71901. var meshName;
  71902. // Hand
  71903. if (this.hand === 'left') {
  71904. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71905. }
  71906. else { // Right is the default if no hand is specified
  71907. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71908. }
  71909. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71910. /*
  71911. Parent Mesh name: oculus_touch_left
  71912. - body
  71913. - trigger
  71914. - thumbstick
  71915. - grip
  71916. - button_y
  71917. - button_x
  71918. - button_enter
  71919. */
  71920. _this._defaultModel = newMeshes[1];
  71921. _this.attachToMesh(_this._defaultModel);
  71922. if (meshLoaded) {
  71923. meshLoaded(_this._defaultModel);
  71924. }
  71925. });
  71926. };
  71927. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71928. /**
  71929. * Fired when the A button on this controller is modified
  71930. */
  71931. get: function () {
  71932. if (this.hand === 'right') {
  71933. return this.onMainButtonStateChangedObservable;
  71934. }
  71935. else {
  71936. throw new Error('No A button on left hand');
  71937. }
  71938. },
  71939. enumerable: true,
  71940. configurable: true
  71941. });
  71942. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71943. /**
  71944. * Fired when the B button on this controller is modified
  71945. */
  71946. get: function () {
  71947. if (this.hand === 'right') {
  71948. return this.onSecondaryButtonStateChangedObservable;
  71949. }
  71950. else {
  71951. throw new Error('No B button on left hand');
  71952. }
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71958. /**
  71959. * Fired when the X button on this controller is modified
  71960. */
  71961. get: function () {
  71962. if (this.hand === 'left') {
  71963. return this.onMainButtonStateChangedObservable;
  71964. }
  71965. else {
  71966. throw new Error('No X button on right hand');
  71967. }
  71968. },
  71969. enumerable: true,
  71970. configurable: true
  71971. });
  71972. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71973. /**
  71974. * Fired when the Y button on this controller is modified
  71975. */
  71976. get: function () {
  71977. if (this.hand === 'left') {
  71978. return this.onSecondaryButtonStateChangedObservable;
  71979. }
  71980. else {
  71981. throw new Error('No Y button on right hand');
  71982. }
  71983. },
  71984. enumerable: true,
  71985. configurable: true
  71986. });
  71987. /**
  71988. * Called once for each button that changed state since the last frame
  71989. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71990. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71991. * 2) secondary trigger (same)
  71992. * 3) A (right) X (left), touch, pressed = value
  71993. * 4) B / Y
  71994. * 5) thumb rest
  71995. * @param buttonIdx Which button index changed
  71996. * @param state New state of the button
  71997. * @param changes Which properties on the state changed since last frame
  71998. */
  71999. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72000. var notifyObject = state; //{ state: state, changes: changes };
  72001. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72002. switch (buttonIdx) {
  72003. case 0:
  72004. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72005. return;
  72006. case 1: // index trigger
  72007. if (this._defaultModel) {
  72008. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72009. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72010. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72011. }
  72012. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72013. return;
  72014. case 2: // secondary trigger
  72015. if (this._defaultModel) {
  72016. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72017. }
  72018. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72019. return;
  72020. case 3:
  72021. if (this._defaultModel) {
  72022. if (notifyObject.pressed) {
  72023. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72024. }
  72025. else {
  72026. (this._defaultModel.getChildren()[1]).position.y = 0;
  72027. }
  72028. }
  72029. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72030. return;
  72031. case 4:
  72032. if (this._defaultModel) {
  72033. if (notifyObject.pressed) {
  72034. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72035. }
  72036. else {
  72037. (this._defaultModel.getChildren()[2]).position.y = 0;
  72038. }
  72039. }
  72040. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72041. return;
  72042. case 5:
  72043. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72044. return;
  72045. }
  72046. };
  72047. /**
  72048. * Base Url for the controller model.
  72049. */
  72050. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72051. /**
  72052. * File name for the left controller model.
  72053. */
  72054. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72055. /**
  72056. * File name for the right controller model.
  72057. */
  72058. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72059. return OculusTouchController;
  72060. }(BABYLON.WebVRController));
  72061. BABYLON.OculusTouchController = OculusTouchController;
  72062. })(BABYLON || (BABYLON = {}));
  72063. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72064. var BABYLON;
  72065. (function (BABYLON) {
  72066. /**
  72067. * Vive Controller
  72068. */
  72069. var ViveController = /** @class */ (function (_super) {
  72070. __extends(ViveController, _super);
  72071. /**
  72072. * Creates a new ViveController from a gamepad
  72073. * @param vrGamepad the gamepad that the controller should be created from
  72074. */
  72075. function ViveController(vrGamepad) {
  72076. var _this = _super.call(this, vrGamepad) || this;
  72077. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72078. _this._invertLeftStickY = true;
  72079. return _this;
  72080. }
  72081. /**
  72082. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72083. * @param scene scene in which to add meshes
  72084. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72085. */
  72086. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72087. var _this = this;
  72088. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72089. /*
  72090. Parent Mesh name: ViveWand
  72091. - body
  72092. - r_gripper
  72093. - l_gripper
  72094. - menu_button
  72095. - system_button
  72096. - trackpad
  72097. - trigger
  72098. - LED
  72099. */
  72100. _this._defaultModel = newMeshes[1];
  72101. _this.attachToMesh(_this._defaultModel);
  72102. if (meshLoaded) {
  72103. meshLoaded(_this._defaultModel);
  72104. }
  72105. });
  72106. };
  72107. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72108. /**
  72109. * Fired when the left button on this controller is modified
  72110. */
  72111. get: function () {
  72112. return this.onMainButtonStateChangedObservable;
  72113. },
  72114. enumerable: true,
  72115. configurable: true
  72116. });
  72117. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72118. /**
  72119. * Fired when the right button on this controller is modified
  72120. */
  72121. get: function () {
  72122. return this.onMainButtonStateChangedObservable;
  72123. },
  72124. enumerable: true,
  72125. configurable: true
  72126. });
  72127. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72128. /**
  72129. * Fired when the menu button on this controller is modified
  72130. */
  72131. get: function () {
  72132. return this.onSecondaryButtonStateChangedObservable;
  72133. },
  72134. enumerable: true,
  72135. configurable: true
  72136. });
  72137. /**
  72138. * Called once for each button that changed state since the last frame
  72139. * Vive mapping:
  72140. * 0: touchpad
  72141. * 1: trigger
  72142. * 2: left AND right buttons
  72143. * 3: menu button
  72144. * @param buttonIdx Which button index changed
  72145. * @param state New state of the button
  72146. * @param changes Which properties on the state changed since last frame
  72147. */
  72148. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72149. var notifyObject = state; //{ state: state, changes: changes };
  72150. switch (buttonIdx) {
  72151. case 0:
  72152. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72153. return;
  72154. case 1: // index trigger
  72155. if (this._defaultModel) {
  72156. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72157. }
  72158. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72159. return;
  72160. case 2: // left AND right button
  72161. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72162. return;
  72163. case 3:
  72164. if (this._defaultModel) {
  72165. if (notifyObject.pressed) {
  72166. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72167. }
  72168. else {
  72169. (this._defaultModel.getChildren()[2]).position.y = 0;
  72170. }
  72171. }
  72172. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72173. return;
  72174. }
  72175. };
  72176. /**
  72177. * Base Url for the controller model.
  72178. */
  72179. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72180. /**
  72181. * File name for the controller model.
  72182. */
  72183. ViveController.MODEL_FILENAME = 'wand.babylon';
  72184. return ViveController;
  72185. }(BABYLON.WebVRController));
  72186. BABYLON.ViveController = ViveController;
  72187. })(BABYLON || (BABYLON = {}));
  72188. //# sourceMappingURL=babylon.viveController.js.map
  72189. var BABYLON;
  72190. (function (BABYLON) {
  72191. /**
  72192. * Generic Controller
  72193. */
  72194. var GenericController = /** @class */ (function (_super) {
  72195. __extends(GenericController, _super);
  72196. /**
  72197. * Creates a new GenericController from a gamepad
  72198. * @param vrGamepad the gamepad that the controller should be created from
  72199. */
  72200. function GenericController(vrGamepad) {
  72201. return _super.call(this, vrGamepad) || this;
  72202. }
  72203. /**
  72204. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72205. * @param scene scene in which to add meshes
  72206. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72207. */
  72208. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72209. var _this = this;
  72210. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72211. _this._defaultModel = newMeshes[1];
  72212. _this.attachToMesh(_this._defaultModel);
  72213. if (meshLoaded) {
  72214. meshLoaded(_this._defaultModel);
  72215. }
  72216. });
  72217. };
  72218. /**
  72219. * Called once for each button that changed state since the last frame
  72220. * @param buttonIdx Which button index changed
  72221. * @param state New state of the button
  72222. * @param changes Which properties on the state changed since last frame
  72223. */
  72224. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72225. console.log("Button id: " + buttonIdx + "state: ");
  72226. console.dir(state);
  72227. };
  72228. /**
  72229. * Base Url for the controller model.
  72230. */
  72231. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72232. /**
  72233. * File name for the controller model.
  72234. */
  72235. GenericController.MODEL_FILENAME = 'generic.babylon';
  72236. return GenericController;
  72237. }(BABYLON.WebVRController));
  72238. BABYLON.GenericController = GenericController;
  72239. })(BABYLON || (BABYLON = {}));
  72240. //# sourceMappingURL=babylon.genericController.js.map
  72241. var BABYLON;
  72242. (function (BABYLON) {
  72243. /**
  72244. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72245. */
  72246. var LoadedMeshInfo = /** @class */ (function () {
  72247. function LoadedMeshInfo() {
  72248. /**
  72249. * Map of the button meshes contained in the controller
  72250. */
  72251. this.buttonMeshes = {};
  72252. /**
  72253. * Map of the axis meshes contained in the controller
  72254. */
  72255. this.axisMeshes = {};
  72256. }
  72257. return LoadedMeshInfo;
  72258. }());
  72259. /**
  72260. * Defines the WindowsMotionController object that the state of the windows motion controller
  72261. */
  72262. var WindowsMotionController = /** @class */ (function (_super) {
  72263. __extends(WindowsMotionController, _super);
  72264. /**
  72265. * Creates a new WindowsMotionController from a gamepad
  72266. * @param vrGamepad the gamepad that the controller should be created from
  72267. */
  72268. function WindowsMotionController(vrGamepad) {
  72269. var _this = _super.call(this, vrGamepad) || this;
  72270. _this._mapping = {
  72271. // Semantic button names
  72272. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72273. // A mapping of the button name to glTF model node name
  72274. // that should be transformed by button value.
  72275. buttonMeshNames: {
  72276. 'trigger': 'SELECT',
  72277. 'menu': 'MENU',
  72278. 'grip': 'GRASP',
  72279. 'thumbstick': 'THUMBSTICK_PRESS',
  72280. 'trackpad': 'TOUCHPAD_PRESS'
  72281. },
  72282. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72283. buttonObservableNames: {
  72284. 'trigger': 'onTriggerStateChangedObservable',
  72285. 'menu': 'onSecondaryButtonStateChangedObservable',
  72286. 'grip': 'onMainButtonStateChangedObservable',
  72287. 'thumbstick': 'onPadStateChangedObservable',
  72288. 'trackpad': 'onTrackpadChangedObservable'
  72289. },
  72290. // A mapping of the axis name to glTF model node name
  72291. // that should be transformed by axis value.
  72292. // This array mirrors the browserGamepad.axes array, such that
  72293. // the mesh corresponding to axis 0 is in this array index 0.
  72294. axisMeshNames: [
  72295. 'THUMBSTICK_X',
  72296. 'THUMBSTICK_Y',
  72297. 'TOUCHPAD_TOUCH_X',
  72298. 'TOUCHPAD_TOUCH_Y'
  72299. ],
  72300. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72301. };
  72302. /**
  72303. * Fired when the trackpad on this controller is clicked
  72304. */
  72305. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72306. /**
  72307. * Fired when the trackpad on this controller is modified
  72308. */
  72309. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72310. /**
  72311. * The current x and y values of this controller's trackpad
  72312. */
  72313. _this.trackpad = { x: 0, y: 0 };
  72314. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72315. _this._loadedMeshInfo = null;
  72316. return _this;
  72317. }
  72318. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72319. /**
  72320. * Fired when the trigger on this controller is modified
  72321. */
  72322. get: function () {
  72323. return this.onTriggerStateChangedObservable;
  72324. },
  72325. enumerable: true,
  72326. configurable: true
  72327. });
  72328. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72329. /**
  72330. * Fired when the menu button on this controller is modified
  72331. */
  72332. get: function () {
  72333. return this.onSecondaryButtonStateChangedObservable;
  72334. },
  72335. enumerable: true,
  72336. configurable: true
  72337. });
  72338. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72339. /**
  72340. * Fired when the grip button on this controller is modified
  72341. */
  72342. get: function () {
  72343. return this.onMainButtonStateChangedObservable;
  72344. },
  72345. enumerable: true,
  72346. configurable: true
  72347. });
  72348. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72349. /**
  72350. * Fired when the thumbstick button on this controller is modified
  72351. */
  72352. get: function () {
  72353. return this.onPadStateChangedObservable;
  72354. },
  72355. enumerable: true,
  72356. configurable: true
  72357. });
  72358. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72359. /**
  72360. * Fired when the touchpad button on this controller is modified
  72361. */
  72362. get: function () {
  72363. return this.onTrackpadChangedObservable;
  72364. },
  72365. enumerable: true,
  72366. configurable: true
  72367. });
  72368. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72369. /**
  72370. * Fired when the touchpad values on this controller are modified
  72371. */
  72372. get: function () {
  72373. return this.onTrackpadValuesChangedObservable;
  72374. },
  72375. enumerable: true,
  72376. configurable: true
  72377. });
  72378. WindowsMotionController.prototype._updateTrackpad = function () {
  72379. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72380. this.trackpad.x = this.browserGamepad["axes"][2];
  72381. this.trackpad.y = this.browserGamepad["axes"][3];
  72382. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72383. }
  72384. };
  72385. /**
  72386. * Called once per frame by the engine.
  72387. */
  72388. WindowsMotionController.prototype.update = function () {
  72389. _super.prototype.update.call(this);
  72390. if (this.browserGamepad.axes) {
  72391. this._updateTrackpad();
  72392. // Only need to animate axes if there is a loaded mesh
  72393. if (this._loadedMeshInfo) {
  72394. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72395. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72396. }
  72397. }
  72398. }
  72399. };
  72400. /**
  72401. * Called once for each button that changed state since the last frame
  72402. * @param buttonIdx Which button index changed
  72403. * @param state New state of the button
  72404. * @param changes Which properties on the state changed since last frame
  72405. */
  72406. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72407. var buttonName = this._mapping.buttons[buttonIdx];
  72408. if (!buttonName) {
  72409. return;
  72410. }
  72411. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72412. this._updateTrackpad();
  72413. // Only emit events for buttons that we know how to map from index to name
  72414. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72415. if (observable) {
  72416. observable.notifyObservers(state);
  72417. }
  72418. this._lerpButtonTransform(buttonName, state.value);
  72419. };
  72420. /**
  72421. * Moves the buttons on the controller mesh based on their current state
  72422. * @param buttonName the name of the button to move
  72423. * @param buttonValue the value of the button which determines the buttons new position
  72424. */
  72425. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72426. // If there is no loaded mesh, there is nothing to transform.
  72427. if (!this._loadedMeshInfo) {
  72428. return;
  72429. }
  72430. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72431. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72432. return;
  72433. }
  72434. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72435. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72436. };
  72437. /**
  72438. * Moves the axis on the controller mesh based on its current state
  72439. * @param axis the index of the axis
  72440. * @param axisValue the value of the axis which determines the meshes new position
  72441. * @hidden
  72442. */
  72443. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72444. if (!this._loadedMeshInfo) {
  72445. return;
  72446. }
  72447. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72448. if (!meshInfo) {
  72449. return;
  72450. }
  72451. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72452. return;
  72453. }
  72454. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72455. var lerpValue = axisValue * 0.5 + 0.5;
  72456. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72457. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72458. };
  72459. /**
  72460. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72461. * @param scene scene in which to add meshes
  72462. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72463. */
  72464. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72465. var _this = this;
  72466. if (forceDefault === void 0) { forceDefault = false; }
  72467. var path;
  72468. var filename;
  72469. // Checking if GLB loader is present
  72470. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72471. // Determine the device specific folder based on the ID suffix
  72472. var device = 'default';
  72473. if (this.id && !forceDefault) {
  72474. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72475. device = ((match && match[0]) || device);
  72476. }
  72477. // Hand
  72478. if (this.hand === 'left') {
  72479. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72480. }
  72481. else { // Right is the default if no hand is specified
  72482. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72483. }
  72484. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72485. }
  72486. else {
  72487. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72488. path = BABYLON.GenericController.MODEL_BASE_URL;
  72489. filename = BABYLON.GenericController.MODEL_FILENAME;
  72490. }
  72491. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72492. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72493. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72494. if (!_this._loadedMeshInfo) {
  72495. return;
  72496. }
  72497. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72498. _this.attachToMesh(_this._defaultModel);
  72499. if (meshLoaded) {
  72500. meshLoaded(_this._defaultModel);
  72501. }
  72502. }, null, function (scene, message) {
  72503. BABYLON.Tools.Log(message);
  72504. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72505. if (!forceDefault) {
  72506. _this.initControllerMesh(scene, meshLoaded, true);
  72507. }
  72508. });
  72509. };
  72510. /**
  72511. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72512. * can be transformed by button presses and axes values, based on this._mapping.
  72513. *
  72514. * @param scene scene in which the meshes exist
  72515. * @param meshes list of meshes that make up the controller model to process
  72516. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72517. */
  72518. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72519. var loadedMeshInfo = null;
  72520. // Create a new mesh to contain the glTF hierarchy
  72521. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72522. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72523. var childMesh = null;
  72524. for (var i = 0; i < meshes.length; i++) {
  72525. var mesh = meshes[i];
  72526. if (!mesh.parent) {
  72527. // Exclude controller meshes from picking results
  72528. mesh.isPickable = false;
  72529. // Handle root node, attach to the new parentMesh
  72530. childMesh = mesh;
  72531. break;
  72532. }
  72533. }
  72534. if (childMesh) {
  72535. childMesh.setParent(parentMesh);
  72536. // Create our mesh info. Note that this method will always return non-null.
  72537. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72538. }
  72539. else {
  72540. BABYLON.Tools.Warn('Could not find root node in model file.');
  72541. }
  72542. return loadedMeshInfo;
  72543. };
  72544. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72545. var loadedMeshInfo = new LoadedMeshInfo();
  72546. var i;
  72547. loadedMeshInfo.rootNode = rootNode;
  72548. // Reset the caches
  72549. loadedMeshInfo.buttonMeshes = {};
  72550. loadedMeshInfo.axisMeshes = {};
  72551. // Button Meshes
  72552. for (i = 0; i < this._mapping.buttons.length; i++) {
  72553. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72554. if (!buttonMeshName) {
  72555. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72556. continue;
  72557. }
  72558. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72559. if (!buttonMesh) {
  72560. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72561. continue;
  72562. }
  72563. var buttonMeshInfo = {
  72564. index: i,
  72565. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72566. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72567. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72568. };
  72569. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72570. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72571. }
  72572. else {
  72573. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72574. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72575. '(VALUE: ' + !!buttonMeshInfo.value +
  72576. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72577. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72578. ')');
  72579. }
  72580. }
  72581. // Axis Meshes
  72582. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72583. var axisMeshName = this._mapping.axisMeshNames[i];
  72584. if (!axisMeshName) {
  72585. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72586. continue;
  72587. }
  72588. var axisMesh = getChildByName(rootNode, axisMeshName);
  72589. if (!axisMesh) {
  72590. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72591. continue;
  72592. }
  72593. var axisMeshInfo = {
  72594. index: i,
  72595. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72596. min: getImmediateChildByName(axisMesh, 'MIN'),
  72597. max: getImmediateChildByName(axisMesh, 'MAX')
  72598. };
  72599. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72600. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72601. }
  72602. else {
  72603. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72604. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72605. '(VALUE: ' + !!axisMeshInfo.value +
  72606. ', MIN: ' + !!axisMeshInfo.min +
  72607. ', MAX:' + !!axisMeshInfo.max +
  72608. ')');
  72609. }
  72610. }
  72611. // Pointing Ray
  72612. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72613. if (!loadedMeshInfo.pointingPoseNode) {
  72614. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72615. }
  72616. else {
  72617. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72618. }
  72619. return loadedMeshInfo;
  72620. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72621. function getChildByName(node, name) {
  72622. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72623. }
  72624. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72625. function getImmediateChildByName(node, name) {
  72626. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72627. }
  72628. };
  72629. /**
  72630. * Gets the ray of the controller in the direction the controller is pointing
  72631. * @param length the length the resulting ray should be
  72632. * @returns a ray in the direction the controller is pointing
  72633. */
  72634. WindowsMotionController.prototype.getForwardRay = function (length) {
  72635. if (length === void 0) { length = 100; }
  72636. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72637. return _super.prototype.getForwardRay.call(this, length);
  72638. }
  72639. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72640. var origin = m.getTranslation();
  72641. var forward = new BABYLON.Vector3(0, 0, -1);
  72642. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72643. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72644. return new BABYLON.Ray(origin, direction, length);
  72645. };
  72646. /**
  72647. * Disposes of the controller
  72648. */
  72649. WindowsMotionController.prototype.dispose = function () {
  72650. _super.prototype.dispose.call(this);
  72651. this.onTrackpadChangedObservable.clear();
  72652. };
  72653. /**
  72654. * The base url used to load the left and right controller models
  72655. */
  72656. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72657. /**
  72658. * The name of the left controller model file
  72659. */
  72660. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72661. /**
  72662. * The name of the right controller model file
  72663. */
  72664. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72665. /**
  72666. * The controller name prefix for this controller type
  72667. */
  72668. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72669. /**
  72670. * The controller id pattern for this controller type
  72671. */
  72672. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72673. return WindowsMotionController;
  72674. }(BABYLON.WebVRController));
  72675. BABYLON.WindowsMotionController = WindowsMotionController;
  72676. })(BABYLON || (BABYLON = {}));
  72677. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72678. var BABYLON;
  72679. (function (BABYLON) {
  72680. /**
  72681. * Gear VR Controller
  72682. */
  72683. var GearVRController = /** @class */ (function (_super) {
  72684. __extends(GearVRController, _super);
  72685. /**
  72686. * Creates a new GearVRController from a gamepad
  72687. * @param vrGamepad the gamepad that the controller should be created from
  72688. */
  72689. function GearVRController(vrGamepad) {
  72690. var _this = _super.call(this, vrGamepad) || this;
  72691. _this._maxRotationDistFromHeadset = Math.PI / 5;
  72692. _this._draggedRoomRotation = 0;
  72693. _this._tmpVector = new BABYLON.Vector3();
  72694. _this._buttonIndexToObservableNameMap = [
  72695. 'onTrackpadChangedObservable',
  72696. 'onTriggerStateChangedObservable' // Trigger
  72697. ];
  72698. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72699. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72700. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  72701. return _this;
  72702. }
  72703. /**
  72704. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72705. * @param poseData raw pose fromthe device
  72706. */
  72707. GearVRController.prototype.updateFromDevice = function (poseData) {
  72708. _super.prototype.updateFromDevice.call(this, poseData);
  72709. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  72710. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  72711. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  72712. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  72713. // Find the radian distance away that the headset is from the controllers rotation
  72714. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  72715. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  72716. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  72717. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  72718. this._draggedRoomRotation += rotationAmount;
  72719. // Rotate controller around headset
  72720. var sin = Math.sin(-rotationAmount);
  72721. var cos = Math.cos(-rotationAmount);
  72722. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  72723. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  72724. }
  72725. }
  72726. }
  72727. };
  72728. /**
  72729. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72730. * @param scene scene in which to add meshes
  72731. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72732. */
  72733. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72734. var _this = this;
  72735. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72736. // Offset the controller so it will rotate around the users wrist
  72737. var mesh = new BABYLON.Mesh("", scene);
  72738. newMeshes[1].parent = mesh;
  72739. newMeshes[1].position.z = -0.15;
  72740. _this._defaultModel = mesh;
  72741. _this.attachToMesh(_this._defaultModel);
  72742. if (meshLoaded) {
  72743. meshLoaded(_this._defaultModel);
  72744. }
  72745. });
  72746. };
  72747. /**
  72748. * Called once for each button that changed state since the last frame
  72749. * @param buttonIdx Which button index changed
  72750. * @param state New state of the button
  72751. * @param changes Which properties on the state changed since last frame
  72752. */
  72753. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72754. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72755. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72756. // Only emit events for buttons that we know how to map from index to observable
  72757. var observable = this[observableName];
  72758. if (observable) {
  72759. observable.notifyObservers(state);
  72760. }
  72761. }
  72762. };
  72763. /**
  72764. * Base Url for the controller model.
  72765. */
  72766. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72767. /**
  72768. * File name for the controller model.
  72769. */
  72770. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72771. /**
  72772. * Gamepad Id prefix used to identify this controller.
  72773. */
  72774. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72775. return GearVRController;
  72776. }(BABYLON.WebVRController));
  72777. BABYLON.GearVRController = GearVRController;
  72778. })(BABYLON || (BABYLON = {}));
  72779. //# sourceMappingURL=babylon.gearVRController.js.map
  72780. var BABYLON;
  72781. (function (BABYLON) {
  72782. /**
  72783. * Google Daydream controller
  72784. */
  72785. var DaydreamController = /** @class */ (function (_super) {
  72786. __extends(DaydreamController, _super);
  72787. /**
  72788. * Creates a new DaydreamController from a gamepad
  72789. * @param vrGamepad the gamepad that the controller should be created from
  72790. */
  72791. function DaydreamController(vrGamepad) {
  72792. var _this = _super.call(this, vrGamepad) || this;
  72793. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72794. return _this;
  72795. }
  72796. /**
  72797. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72798. * @param scene scene in which to add meshes
  72799. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72800. */
  72801. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72802. var _this = this;
  72803. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72804. _this._defaultModel = newMeshes[1];
  72805. _this.attachToMesh(_this._defaultModel);
  72806. if (meshLoaded) {
  72807. meshLoaded(_this._defaultModel);
  72808. }
  72809. });
  72810. };
  72811. /**
  72812. * Called once for each button that changed state since the last frame
  72813. * @param buttonIdx Which button index changed
  72814. * @param state New state of the button
  72815. * @param changes Which properties on the state changed since last frame
  72816. */
  72817. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72818. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72819. if (buttonIdx === 0) {
  72820. var observable = this.onTriggerStateChangedObservable;
  72821. if (observable) {
  72822. observable.notifyObservers(state);
  72823. }
  72824. }
  72825. else {
  72826. // If the app or home buttons are ever made available
  72827. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72828. }
  72829. };
  72830. /**
  72831. * Base Url for the controller model.
  72832. */
  72833. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72834. /**
  72835. * File name for the controller model.
  72836. */
  72837. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72838. /**
  72839. * Gamepad Id prefix used to identify Daydream Controller.
  72840. */
  72841. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72842. return DaydreamController;
  72843. }(BABYLON.WebVRController));
  72844. BABYLON.DaydreamController = DaydreamController;
  72845. })(BABYLON || (BABYLON = {}));
  72846. //# sourceMappingURL=babylon.daydreamController.js.map
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  72850. get: function () {
  72851. if (!this._gamepadManager) {
  72852. this._gamepadManager = new BABYLON.GamepadManager(this);
  72853. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  72854. if (!component) {
  72855. component = new GamepadSystemSceneComponent(this);
  72856. this._addComponent(component);
  72857. }
  72858. }
  72859. return this._gamepadManager;
  72860. },
  72861. enumerable: true,
  72862. configurable: true
  72863. });
  72864. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  72865. this.add(new BABYLON.FreeCameraGamepadInput());
  72866. return this;
  72867. };
  72868. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  72869. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  72870. return this;
  72871. };
  72872. /**
  72873. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  72874. */
  72875. var GamepadSystemSceneComponent = /** @class */ (function () {
  72876. /**
  72877. * Creates a new instance of the component for the given scene
  72878. * @param scene Defines the scene to register the component in
  72879. */
  72880. function GamepadSystemSceneComponent(scene) {
  72881. /**
  72882. * The component name helpfull to identify the component in the list of scene components.
  72883. */
  72884. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  72885. this.scene = scene;
  72886. }
  72887. /**
  72888. * Registers the component in a given scene
  72889. */
  72890. GamepadSystemSceneComponent.prototype.register = function () {
  72891. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  72892. };
  72893. /**
  72894. * Rebuilds the elements related to this component in case of
  72895. * context lost for instance.
  72896. */
  72897. GamepadSystemSceneComponent.prototype.rebuild = function () {
  72898. // Nothing to do for gamepads
  72899. };
  72900. /**
  72901. * Disposes the component and the associated ressources
  72902. */
  72903. GamepadSystemSceneComponent.prototype.dispose = function () {
  72904. var gamepadManager = this.scene._gamepadManager;
  72905. if (gamepadManager) {
  72906. gamepadManager.dispose();
  72907. this.scene._gamepadManager = null;
  72908. }
  72909. };
  72910. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  72911. var gamepadManager = this.scene._gamepadManager;
  72912. if (gamepadManager && gamepadManager._isMonitoring) {
  72913. gamepadManager._checkGamepadsStatus();
  72914. }
  72915. };
  72916. return GamepadSystemSceneComponent;
  72917. }());
  72918. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  72919. })(BABYLON || (BABYLON = {}));
  72920. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  72921. var BABYLON;
  72922. (function (BABYLON) {
  72923. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  72924. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  72925. });
  72926. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  72927. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  72928. });
  72929. var FollowCamera = /** @class */ (function (_super) {
  72930. __extends(FollowCamera, _super);
  72931. function FollowCamera(name, position, scene, lockedTarget) {
  72932. if (lockedTarget === void 0) { lockedTarget = null; }
  72933. var _this = _super.call(this, name, position, scene) || this;
  72934. _this.radius = 12;
  72935. _this.rotationOffset = 0;
  72936. _this.heightOffset = 4;
  72937. _this.cameraAcceleration = 0.05;
  72938. _this.maxCameraSpeed = 20;
  72939. _this.lockedTarget = lockedTarget;
  72940. return _this;
  72941. }
  72942. FollowCamera.prototype.getRadians = function (degrees) {
  72943. return degrees * Math.PI / 180;
  72944. };
  72945. FollowCamera.prototype.follow = function (cameraTarget) {
  72946. if (!cameraTarget)
  72947. return;
  72948. var yRotation;
  72949. if (cameraTarget.rotationQuaternion) {
  72950. var rotMatrix = new BABYLON.Matrix();
  72951. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72952. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72953. }
  72954. else {
  72955. yRotation = cameraTarget.rotation.y;
  72956. }
  72957. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72958. var targetPosition = cameraTarget.getAbsolutePosition();
  72959. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72960. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72961. var dx = targetX - this.position.x;
  72962. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72963. var dz = (targetZ) - this.position.z;
  72964. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72965. var vy = dy * this.cameraAcceleration;
  72966. var vz = dz * this.cameraAcceleration * 2;
  72967. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72968. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72969. }
  72970. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72971. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72972. }
  72973. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72974. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72975. }
  72976. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72977. this.setTarget(targetPosition);
  72978. };
  72979. FollowCamera.prototype._checkInputs = function () {
  72980. _super.prototype._checkInputs.call(this);
  72981. if (this.lockedTarget) {
  72982. this.follow(this.lockedTarget);
  72983. }
  72984. };
  72985. FollowCamera.prototype.getClassName = function () {
  72986. return "FollowCamera";
  72987. };
  72988. __decorate([
  72989. BABYLON.serialize()
  72990. ], FollowCamera.prototype, "radius", void 0);
  72991. __decorate([
  72992. BABYLON.serialize()
  72993. ], FollowCamera.prototype, "rotationOffset", void 0);
  72994. __decorate([
  72995. BABYLON.serialize()
  72996. ], FollowCamera.prototype, "heightOffset", void 0);
  72997. __decorate([
  72998. BABYLON.serialize()
  72999. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73000. __decorate([
  73001. BABYLON.serialize()
  73002. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73003. __decorate([
  73004. BABYLON.serializeAsMeshReference("lockedTargetId")
  73005. ], FollowCamera.prototype, "lockedTarget", void 0);
  73006. return FollowCamera;
  73007. }(BABYLON.TargetCamera));
  73008. BABYLON.FollowCamera = FollowCamera;
  73009. var ArcFollowCamera = /** @class */ (function (_super) {
  73010. __extends(ArcFollowCamera, _super);
  73011. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73012. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73013. _this.alpha = alpha;
  73014. _this.beta = beta;
  73015. _this.radius = radius;
  73016. _this.target = target;
  73017. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73018. _this.follow();
  73019. return _this;
  73020. }
  73021. ArcFollowCamera.prototype.follow = function () {
  73022. if (!this.target) {
  73023. return;
  73024. }
  73025. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73026. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73027. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73028. var targetPosition = this.target.getAbsolutePosition();
  73029. this.position = targetPosition.add(this._cartesianCoordinates);
  73030. this.setTarget(targetPosition);
  73031. };
  73032. ArcFollowCamera.prototype._checkInputs = function () {
  73033. _super.prototype._checkInputs.call(this);
  73034. this.follow();
  73035. };
  73036. ArcFollowCamera.prototype.getClassName = function () {
  73037. return "ArcFollowCamera";
  73038. };
  73039. return ArcFollowCamera;
  73040. }(BABYLON.TargetCamera));
  73041. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73042. })(BABYLON || (BABYLON = {}));
  73043. //# sourceMappingURL=babylon.followCamera.js.map
  73044. var BABYLON;
  73045. (function (BABYLON) {
  73046. // We're mainly based on the logic defined into the FreeCamera code
  73047. var UniversalCamera = /** @class */ (function (_super) {
  73048. __extends(UniversalCamera, _super);
  73049. //-- end properties for backward compatibility for inputs
  73050. function UniversalCamera(name, position, scene) {
  73051. var _this = _super.call(this, name, position, scene) || this;
  73052. _this.inputs.addGamepad();
  73053. return _this;
  73054. }
  73055. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73056. //-- Begin properties for backward compatibility for inputs
  73057. get: function () {
  73058. var gamepad = this.inputs.attached["gamepad"];
  73059. if (gamepad)
  73060. return gamepad.gamepadAngularSensibility;
  73061. return 0;
  73062. },
  73063. set: function (value) {
  73064. var gamepad = this.inputs.attached["gamepad"];
  73065. if (gamepad)
  73066. gamepad.gamepadAngularSensibility = value;
  73067. },
  73068. enumerable: true,
  73069. configurable: true
  73070. });
  73071. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73072. get: function () {
  73073. var gamepad = this.inputs.attached["gamepad"];
  73074. if (gamepad)
  73075. return gamepad.gamepadMoveSensibility;
  73076. return 0;
  73077. },
  73078. set: function (value) {
  73079. var gamepad = this.inputs.attached["gamepad"];
  73080. if (gamepad)
  73081. gamepad.gamepadMoveSensibility = value;
  73082. },
  73083. enumerable: true,
  73084. configurable: true
  73085. });
  73086. UniversalCamera.prototype.getClassName = function () {
  73087. return "UniversalCamera";
  73088. };
  73089. return UniversalCamera;
  73090. }(BABYLON.TouchCamera));
  73091. BABYLON.UniversalCamera = UniversalCamera;
  73092. })(BABYLON || (BABYLON = {}));
  73093. //# sourceMappingURL=babylon.universalCamera.js.map
  73094. var BABYLON;
  73095. (function (BABYLON) {
  73096. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  73097. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  73098. });
  73099. // We're mainly based on the logic defined into the FreeCamera code
  73100. var GamepadCamera = /** @class */ (function (_super) {
  73101. __extends(GamepadCamera, _super);
  73102. //-- end properties for backward compatibility for inputs
  73103. function GamepadCamera(name, position, scene) {
  73104. return _super.call(this, name, position, scene) || this;
  73105. }
  73106. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73107. //-- Begin properties for backward compatibility for inputs
  73108. get: function () {
  73109. var gamepad = this.inputs.attached["gamepad"];
  73110. if (gamepad)
  73111. return gamepad.gamepadAngularSensibility;
  73112. return 0;
  73113. },
  73114. set: function (value) {
  73115. var gamepad = this.inputs.attached["gamepad"];
  73116. if (gamepad)
  73117. gamepad.gamepadAngularSensibility = value;
  73118. },
  73119. enumerable: true,
  73120. configurable: true
  73121. });
  73122. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73123. get: function () {
  73124. var gamepad = this.inputs.attached["gamepad"];
  73125. if (gamepad)
  73126. return gamepad.gamepadMoveSensibility;
  73127. return 0;
  73128. },
  73129. set: function (value) {
  73130. var gamepad = this.inputs.attached["gamepad"];
  73131. if (gamepad)
  73132. gamepad.gamepadMoveSensibility = value;
  73133. },
  73134. enumerable: true,
  73135. configurable: true
  73136. });
  73137. GamepadCamera.prototype.getClassName = function () {
  73138. return "GamepadCamera";
  73139. };
  73140. return GamepadCamera;
  73141. }(BABYLON.UniversalCamera));
  73142. BABYLON.GamepadCamera = GamepadCamera;
  73143. })(BABYLON || (BABYLON = {}));
  73144. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73145. var BABYLON;
  73146. (function (BABYLON) {
  73147. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73148. function PostProcessRenderPipelineManager() {
  73149. this._renderPipelines = {};
  73150. }
  73151. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73152. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73153. };
  73154. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73155. if (unique === void 0) { unique = false; }
  73156. var renderPipeline = this._renderPipelines[renderPipelineName];
  73157. if (!renderPipeline) {
  73158. return;
  73159. }
  73160. renderPipeline._attachCameras(cameras, unique);
  73161. };
  73162. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73163. var renderPipeline = this._renderPipelines[renderPipelineName];
  73164. if (!renderPipeline) {
  73165. return;
  73166. }
  73167. renderPipeline._detachCameras(cameras);
  73168. };
  73169. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73170. var renderPipeline = this._renderPipelines[renderPipelineName];
  73171. if (!renderPipeline) {
  73172. return;
  73173. }
  73174. renderPipeline._enableEffect(renderEffectName, cameras);
  73175. };
  73176. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73177. var renderPipeline = this._renderPipelines[renderPipelineName];
  73178. if (!renderPipeline) {
  73179. return;
  73180. }
  73181. renderPipeline._disableEffect(renderEffectName, cameras);
  73182. };
  73183. PostProcessRenderPipelineManager.prototype.update = function () {
  73184. for (var renderPipelineName in this._renderPipelines) {
  73185. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73186. var pipeline = this._renderPipelines[renderPipelineName];
  73187. if (!pipeline.isSupported) {
  73188. pipeline.dispose();
  73189. delete this._renderPipelines[renderPipelineName];
  73190. }
  73191. else {
  73192. pipeline._update();
  73193. }
  73194. }
  73195. }
  73196. };
  73197. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73198. for (var renderPipelineName in this._renderPipelines) {
  73199. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73200. var pipeline = this._renderPipelines[renderPipelineName];
  73201. pipeline._rebuild();
  73202. }
  73203. }
  73204. };
  73205. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73206. for (var renderPipelineName in this._renderPipelines) {
  73207. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73208. var pipeline = this._renderPipelines[renderPipelineName];
  73209. pipeline.dispose();
  73210. }
  73211. }
  73212. };
  73213. return PostProcessRenderPipelineManager;
  73214. }());
  73215. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73216. })(BABYLON || (BABYLON = {}));
  73217. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73218. var BABYLON;
  73219. (function (BABYLON) {
  73220. /**
  73221. * This represents a set of one or more post processes in Babylon.
  73222. * A post process can be used to apply a shader to a texture after it is rendered.
  73223. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73224. */
  73225. var PostProcessRenderEffect = /** @class */ (function () {
  73226. /**
  73227. * Instantiates a post process render effect.
  73228. * A post process can be used to apply a shader to a texture after it is rendered.
  73229. * @param engine The engine the effect is tied to
  73230. * @param name The name of the effect
  73231. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73232. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73233. */
  73234. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73235. this._name = name;
  73236. this._singleInstance = singleInstance || true;
  73237. this._getPostProcesses = getPostProcesses;
  73238. this._cameras = {};
  73239. this._indicesForCamera = {};
  73240. this._postProcesses = {};
  73241. }
  73242. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73243. /**
  73244. * Checks if all the post processes in the effect are supported.
  73245. */
  73246. get: function () {
  73247. for (var index in this._postProcesses) {
  73248. if (this._postProcesses.hasOwnProperty(index)) {
  73249. var pps = this._postProcesses[index];
  73250. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73251. if (!pps[ppIndex].isSupported) {
  73252. return false;
  73253. }
  73254. }
  73255. }
  73256. }
  73257. return true;
  73258. },
  73259. enumerable: true,
  73260. configurable: true
  73261. });
  73262. /**
  73263. * Updates the current state of the effect
  73264. */
  73265. PostProcessRenderEffect.prototype._update = function () {
  73266. };
  73267. /**
  73268. * Attaches the effect on cameras
  73269. * @param cameras The camera to attach to.
  73270. */
  73271. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73272. var _this = this;
  73273. var cameraKey;
  73274. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73275. if (!cams) {
  73276. return;
  73277. }
  73278. for (var i = 0; i < cams.length; i++) {
  73279. var camera = cams[i];
  73280. var cameraName = camera.name;
  73281. if (this._singleInstance) {
  73282. cameraKey = 0;
  73283. }
  73284. else {
  73285. cameraKey = cameraName;
  73286. }
  73287. if (!this._postProcesses[cameraKey]) {
  73288. var postProcess = this._getPostProcesses();
  73289. if (postProcess) {
  73290. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73291. }
  73292. }
  73293. if (!this._indicesForCamera[cameraName]) {
  73294. this._indicesForCamera[cameraName] = [];
  73295. }
  73296. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73297. var index = camera.attachPostProcess(postProcess);
  73298. _this._indicesForCamera[cameraName].push(index);
  73299. });
  73300. if (!this._cameras[cameraName]) {
  73301. this._cameras[cameraName] = camera;
  73302. }
  73303. }
  73304. };
  73305. /**
  73306. * Detatches the effect on cameras
  73307. * @param cameras The camera to detatch from.
  73308. */
  73309. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73310. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73311. if (!cams) {
  73312. return;
  73313. }
  73314. for (var i = 0; i < cams.length; i++) {
  73315. var camera = cams[i];
  73316. var cameraName = camera.name;
  73317. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73318. camera.detachPostProcess(postProcess);
  73319. });
  73320. if (this._cameras[cameraName]) {
  73321. //this._indicesForCamera.splice(index, 1);
  73322. this._cameras[cameraName] = null;
  73323. }
  73324. }
  73325. };
  73326. /**
  73327. * Enables the effect on given cameras
  73328. * @param cameras The camera to enable.
  73329. */
  73330. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73331. var _this = this;
  73332. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73333. if (!cams) {
  73334. return;
  73335. }
  73336. for (var i = 0; i < cams.length; i++) {
  73337. var camera = cams[i];
  73338. var cameraName = camera.name;
  73339. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73340. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73341. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73342. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73343. });
  73344. }
  73345. }
  73346. }
  73347. };
  73348. /**
  73349. * Disables the effect on the given cameras
  73350. * @param cameras The camera to disable.
  73351. */
  73352. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73353. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73354. if (!cams) {
  73355. return;
  73356. }
  73357. for (var i = 0; i < cams.length; i++) {
  73358. var camera = cams[i];
  73359. var cameraName = camera.name;
  73360. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73361. camera.detachPostProcess(postProcess);
  73362. });
  73363. }
  73364. };
  73365. /**
  73366. * Gets a list of the post processes contained in the effect.
  73367. * @param camera The camera to get the post processes on.
  73368. * @returns The list of the post processes in the effect.
  73369. */
  73370. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73371. if (this._singleInstance) {
  73372. return this._postProcesses[0];
  73373. }
  73374. else {
  73375. if (!camera) {
  73376. return null;
  73377. }
  73378. return this._postProcesses[camera.name];
  73379. }
  73380. };
  73381. return PostProcessRenderEffect;
  73382. }());
  73383. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73384. })(BABYLON || (BABYLON = {}));
  73385. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73386. var BABYLON;
  73387. (function (BABYLON) {
  73388. var PostProcessRenderPipeline = /** @class */ (function () {
  73389. function PostProcessRenderPipeline(engine, name) {
  73390. this.engine = engine;
  73391. this._name = name;
  73392. this._renderEffects = {};
  73393. this._renderEffectsForIsolatedPass = new Array();
  73394. this._cameras = [];
  73395. }
  73396. PostProcessRenderPipeline.prototype.getClassName = function () {
  73397. return "PostProcessRenderPipeline";
  73398. };
  73399. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73400. get: function () {
  73401. for (var renderEffectName in this._renderEffects) {
  73402. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73403. if (!this._renderEffects[renderEffectName].isSupported) {
  73404. return false;
  73405. }
  73406. }
  73407. }
  73408. return true;
  73409. },
  73410. enumerable: true,
  73411. configurable: true
  73412. });
  73413. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73414. this._renderEffects[renderEffect._name] = renderEffect;
  73415. };
  73416. // private
  73417. PostProcessRenderPipeline.prototype._rebuild = function () {
  73418. };
  73419. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73420. var renderEffects = this._renderEffects[renderEffectName];
  73421. if (!renderEffects) {
  73422. return;
  73423. }
  73424. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73425. };
  73426. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73427. var renderEffects = this._renderEffects[renderEffectName];
  73428. if (!renderEffects) {
  73429. return;
  73430. }
  73431. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73432. };
  73433. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73434. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73435. if (!cams) {
  73436. return;
  73437. }
  73438. var indicesToDelete = [];
  73439. var i;
  73440. for (i = 0; i < cams.length; i++) {
  73441. var camera = cams[i];
  73442. var cameraName = camera.name;
  73443. if (this._cameras.indexOf(camera) === -1) {
  73444. this._cameras[cameraName] = camera;
  73445. }
  73446. else if (unique) {
  73447. indicesToDelete.push(i);
  73448. }
  73449. }
  73450. for (i = 0; i < indicesToDelete.length; i++) {
  73451. cameras.splice(indicesToDelete[i], 1);
  73452. }
  73453. for (var renderEffectName in this._renderEffects) {
  73454. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73455. this._renderEffects[renderEffectName]._attachCameras(cams);
  73456. }
  73457. }
  73458. };
  73459. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73460. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73461. if (!cams) {
  73462. return;
  73463. }
  73464. for (var renderEffectName in this._renderEffects) {
  73465. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73466. this._renderEffects[renderEffectName]._detachCameras(cams);
  73467. }
  73468. }
  73469. for (var i = 0; i < cams.length; i++) {
  73470. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73471. }
  73472. };
  73473. PostProcessRenderPipeline.prototype._update = function () {
  73474. for (var renderEffectName in this._renderEffects) {
  73475. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73476. this._renderEffects[renderEffectName]._update();
  73477. }
  73478. }
  73479. for (var i = 0; i < this._cameras.length; i++) {
  73480. var cameraName = this._cameras[i].name;
  73481. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73482. this._renderEffectsForIsolatedPass[cameraName]._update();
  73483. }
  73484. }
  73485. };
  73486. PostProcessRenderPipeline.prototype._reset = function () {
  73487. this._renderEffects = {};
  73488. this._renderEffectsForIsolatedPass = new Array();
  73489. };
  73490. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73491. // 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)
  73492. var effectKeys = Object.keys(this._renderEffects);
  73493. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73494. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73495. if (postProcesses) {
  73496. postProcesses[0].samples = sampleCount;
  73497. return true;
  73498. }
  73499. }
  73500. return false;
  73501. };
  73502. PostProcessRenderPipeline.prototype.dispose = function () {
  73503. // Must be implemented by children
  73504. };
  73505. __decorate([
  73506. BABYLON.serialize()
  73507. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73508. return PostProcessRenderPipeline;
  73509. }());
  73510. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73511. })(BABYLON || (BABYLON = {}));
  73512. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73513. var BABYLON;
  73514. (function (BABYLON) {
  73515. /**
  73516. * This represents a depth renderer in Babylon.
  73517. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73518. */
  73519. var DepthRenderer = /** @class */ (function () {
  73520. /**
  73521. * Instantiates a depth renderer
  73522. * @param scene The scene the renderer belongs to
  73523. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73524. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73525. */
  73526. function DepthRenderer(scene, type, camera) {
  73527. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73528. if (camera === void 0) { camera = null; }
  73529. var _this = this;
  73530. this._scene = scene;
  73531. this._camera = camera;
  73532. var engine = scene.getEngine();
  73533. // Render target
  73534. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73535. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73536. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73537. this._depthMap.refreshRate = 1;
  73538. this._depthMap.renderParticles = false;
  73539. this._depthMap.renderList = null;
  73540. // Camera to get depth map from to support multiple concurrent cameras
  73541. this._depthMap.activeCamera = this._camera;
  73542. this._depthMap.ignoreCameraViewport = true;
  73543. this._depthMap.useCameraPostProcesses = false;
  73544. // set default depth value to 1.0 (far away)
  73545. this._depthMap.onClearObservable.add(function (engine) {
  73546. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73547. });
  73548. // Custom render function
  73549. var renderSubMesh = function (subMesh) {
  73550. var mesh = subMesh.getRenderingMesh();
  73551. var scene = _this._scene;
  73552. var engine = scene.getEngine();
  73553. var material = subMesh.getMaterial();
  73554. if (!material) {
  73555. return;
  73556. }
  73557. // Culling and reverse (right handed system)
  73558. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73559. // Managing instances
  73560. var batch = mesh._getInstancesRenderList(subMesh._id);
  73561. if (batch.mustReturn) {
  73562. return;
  73563. }
  73564. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73565. var camera = _this._camera || scene.activeCamera;
  73566. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73567. engine.enableEffect(_this._effect);
  73568. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73569. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73570. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73571. // Alpha test
  73572. if (material && material.needAlphaTesting()) {
  73573. var alphaTexture = material.getAlphaTestTexture();
  73574. if (alphaTexture) {
  73575. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73576. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73577. }
  73578. }
  73579. // Bones
  73580. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73581. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73582. }
  73583. // Draw
  73584. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73585. }
  73586. };
  73587. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73588. var index;
  73589. if (depthOnlySubMeshes.length) {
  73590. engine.setColorWrite(false);
  73591. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73592. renderSubMesh(depthOnlySubMeshes.data[index]);
  73593. }
  73594. engine.setColorWrite(true);
  73595. }
  73596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73597. renderSubMesh(opaqueSubMeshes.data[index]);
  73598. }
  73599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73600. renderSubMesh(alphaTestSubMeshes.data[index]);
  73601. }
  73602. };
  73603. }
  73604. /**
  73605. * Creates the depth rendering effect and checks if the effect is ready.
  73606. * @param subMesh The submesh to be used to render the depth map of
  73607. * @param useInstances If multiple world instances should be used
  73608. * @returns if the depth renderer is ready to render the depth map
  73609. */
  73610. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73611. var material = subMesh.getMaterial();
  73612. if (material.disableDepthWrite) {
  73613. return false;
  73614. }
  73615. var defines = [];
  73616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73617. var mesh = subMesh.getMesh();
  73618. // Alpha test
  73619. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73620. defines.push("#define ALPHATEST");
  73621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73622. attribs.push(BABYLON.VertexBuffer.UVKind);
  73623. defines.push("#define UV1");
  73624. }
  73625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73626. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73627. defines.push("#define UV2");
  73628. }
  73629. }
  73630. // Bones
  73631. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73634. if (mesh.numBoneInfluencers > 4) {
  73635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73637. }
  73638. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73639. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73640. }
  73641. else {
  73642. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73643. }
  73644. // Instances
  73645. if (useInstances) {
  73646. defines.push("#define INSTANCES");
  73647. attribs.push("world0");
  73648. attribs.push("world1");
  73649. attribs.push("world2");
  73650. attribs.push("world3");
  73651. }
  73652. // Get correct effect
  73653. var join = defines.join("\n");
  73654. if (this._cachedDefines !== join) {
  73655. this._cachedDefines = join;
  73656. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73657. }
  73658. return this._effect.isReady();
  73659. };
  73660. /**
  73661. * Gets the texture which the depth map will be written to.
  73662. * @returns The depth map texture
  73663. */
  73664. DepthRenderer.prototype.getDepthMap = function () {
  73665. return this._depthMap;
  73666. };
  73667. /**
  73668. * Disposes of the depth renderer.
  73669. */
  73670. DepthRenderer.prototype.dispose = function () {
  73671. this._depthMap.dispose();
  73672. };
  73673. return DepthRenderer;
  73674. }());
  73675. BABYLON.DepthRenderer = DepthRenderer;
  73676. })(BABYLON || (BABYLON = {}));
  73677. //# sourceMappingURL=babylon.depthRenderer.js.map
  73678. var BABYLON;
  73679. (function (BABYLON) {
  73680. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73681. __extends(SSAORenderingPipeline, _super);
  73682. /**
  73683. * @constructor
  73684. * @param {string} name - The rendering pipeline name
  73685. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73686. * @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 }
  73687. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73688. */
  73689. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73690. var _this = _super.call(this, scene.getEngine(), name) || this;
  73691. // Members
  73692. /**
  73693. * The PassPostProcess id in the pipeline that contains the original scene color
  73694. */
  73695. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73696. /**
  73697. * The SSAO PostProcess id in the pipeline
  73698. */
  73699. _this.SSAORenderEffect = "SSAORenderEffect";
  73700. /**
  73701. * The horizontal blur PostProcess id in the pipeline
  73702. */
  73703. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73704. /**
  73705. * The vertical blur PostProcess id in the pipeline
  73706. */
  73707. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73708. /**
  73709. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73710. */
  73711. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73712. /**
  73713. * The output strength of the SSAO post-process. Default value is 1.0.
  73714. */
  73715. _this.totalStrength = 1.0;
  73716. /**
  73717. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73718. */
  73719. _this.radius = 0.0001;
  73720. /**
  73721. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73722. * Must not be equal to fallOff and superior to fallOff.
  73723. * Default value is 0.975
  73724. */
  73725. _this.area = 0.0075;
  73726. /**
  73727. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73728. * Must not be equal to area and inferior to area.
  73729. * Default value is 0.0
  73730. */
  73731. _this.fallOff = 0.000001;
  73732. /**
  73733. * The base color of the SSAO post-process
  73734. * The final result is "base + ssao" between [0, 1]
  73735. */
  73736. _this.base = 0.5;
  73737. _this._firstUpdate = true;
  73738. _this._scene = scene;
  73739. // Set up assets
  73740. _this._createRandomTexture();
  73741. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73742. var ssaoRatio = ratio.ssaoRatio || ratio;
  73743. var combineRatio = ratio.combineRatio || ratio;
  73744. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73745. _this._createSSAOPostProcess(ssaoRatio);
  73746. _this._createBlurPostProcess(ssaoRatio);
  73747. _this._createSSAOCombinePostProcess(combineRatio);
  73748. // Set up pipeline
  73749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73750. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73751. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73752. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73754. // Finish
  73755. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73756. if (cameras)
  73757. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73758. return _this;
  73759. }
  73760. // Public Methods
  73761. /**
  73762. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73763. */
  73764. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73765. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73766. for (var i = 0; i < this._scene.cameras.length; i++) {
  73767. var camera = this._scene.cameras[i];
  73768. this._originalColorPostProcess.dispose(camera);
  73769. this._ssaoPostProcess.dispose(camera);
  73770. this._blurHPostProcess.dispose(camera);
  73771. this._blurVPostProcess.dispose(camera);
  73772. this._ssaoCombinePostProcess.dispose(camera);
  73773. }
  73774. this._randomTexture.dispose();
  73775. if (disableDepthRender)
  73776. this._scene.disableDepthRenderer();
  73777. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73778. _super.prototype.dispose.call(this);
  73779. };
  73780. // Private Methods
  73781. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73782. var _this = this;
  73783. var size = 16;
  73784. 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);
  73785. 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);
  73786. this._blurHPostProcess.onActivateObservable.add(function () {
  73787. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73788. _this._blurHPostProcess.kernel = size * dw;
  73789. });
  73790. this._blurVPostProcess.onActivateObservable.add(function () {
  73791. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73792. _this._blurVPostProcess.kernel = size * dw;
  73793. });
  73794. };
  73795. SSAORenderingPipeline.prototype._rebuild = function () {
  73796. this._firstUpdate = true;
  73797. _super.prototype._rebuild.call(this);
  73798. };
  73799. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73800. var _this = this;
  73801. var numSamples = 16;
  73802. var sampleSphere = [
  73803. 0.5381, 0.1856, -0.4319,
  73804. 0.1379, 0.2486, 0.4430,
  73805. 0.3371, 0.5679, -0.0057,
  73806. -0.6999, -0.0451, -0.0019,
  73807. 0.0689, -0.1598, -0.8547,
  73808. 0.0560, 0.0069, -0.1843,
  73809. -0.0146, 0.1402, 0.0762,
  73810. 0.0100, -0.1924, -0.0344,
  73811. -0.3577, -0.5301, -0.4358,
  73812. -0.3169, 0.1063, 0.0158,
  73813. 0.0103, -0.5869, 0.0046,
  73814. -0.0897, -0.4940, 0.3287,
  73815. 0.7119, -0.0154, -0.0918,
  73816. -0.0533, 0.0596, -0.5411,
  73817. 0.0352, -0.0631, 0.5460,
  73818. -0.4776, 0.2847, -0.0271
  73819. ];
  73820. var samplesFactor = 1.0 / numSamples;
  73821. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73822. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73823. "area", "fallOff", "base", "range", "viewport"
  73824. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73825. this._ssaoPostProcess.onApply = function (effect) {
  73826. if (_this._firstUpdate) {
  73827. effect.setArray3("sampleSphere", sampleSphere);
  73828. effect.setFloat("samplesFactor", samplesFactor);
  73829. effect.setFloat("randTextureTiles", 4.0);
  73830. }
  73831. effect.setFloat("totalStrength", _this.totalStrength);
  73832. effect.setFloat("radius", _this.radius);
  73833. effect.setFloat("area", _this.area);
  73834. effect.setFloat("fallOff", _this.fallOff);
  73835. effect.setFloat("base", _this.base);
  73836. effect.setTexture("textureSampler", _this._depthTexture);
  73837. effect.setTexture("randomSampler", _this._randomTexture);
  73838. };
  73839. };
  73840. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73841. var _this = this;
  73842. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73843. this._ssaoCombinePostProcess.onApply = function (effect) {
  73844. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73845. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73846. };
  73847. };
  73848. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73849. var size = 512;
  73850. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73851. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73852. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73853. var context = this._randomTexture.getContext();
  73854. var rand = function (min, max) {
  73855. return Math.random() * (max - min) + min;
  73856. };
  73857. var randVector = BABYLON.Vector3.Zero();
  73858. for (var x = 0; x < size; x++) {
  73859. for (var y = 0; y < size; y++) {
  73860. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73861. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73862. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73863. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73864. context.fillRect(x, y, 1, 1);
  73865. }
  73866. }
  73867. this._randomTexture.update(false);
  73868. };
  73869. __decorate([
  73870. BABYLON.serialize()
  73871. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73872. __decorate([
  73873. BABYLON.serialize()
  73874. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73875. __decorate([
  73876. BABYLON.serialize()
  73877. ], SSAORenderingPipeline.prototype, "area", void 0);
  73878. __decorate([
  73879. BABYLON.serialize()
  73880. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73881. __decorate([
  73882. BABYLON.serialize()
  73883. ], SSAORenderingPipeline.prototype, "base", void 0);
  73884. return SSAORenderingPipeline;
  73885. }(BABYLON.PostProcessRenderPipeline));
  73886. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73887. })(BABYLON || (BABYLON = {}));
  73888. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73889. var BABYLON;
  73890. (function (BABYLON) {
  73891. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73892. __extends(SSAO2RenderingPipeline, _super);
  73893. /**
  73894. * @constructor
  73895. * @param {string} name - The rendering pipeline name
  73896. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73897. * @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 }
  73898. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73899. */
  73900. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73901. var _this = _super.call(this, scene.getEngine(), name) || this;
  73902. // Members
  73903. /**
  73904. * The PassPostProcess id in the pipeline that contains the original scene color
  73905. */
  73906. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73907. /**
  73908. * The SSAO PostProcess id in the pipeline
  73909. */
  73910. _this.SSAORenderEffect = "SSAORenderEffect";
  73911. /**
  73912. * The horizontal blur PostProcess id in the pipeline
  73913. */
  73914. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73915. /**
  73916. * The vertical blur PostProcess id in the pipeline
  73917. */
  73918. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73919. /**
  73920. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73921. */
  73922. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73923. /**
  73924. * The output strength of the SSAO post-process. Default value is 1.0.
  73925. */
  73926. _this.totalStrength = 1.0;
  73927. /**
  73928. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73929. */
  73930. _this.maxZ = 100.0;
  73931. /**
  73932. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73933. */
  73934. _this.minZAspect = 0.2;
  73935. /**
  73936. * Number of samples used for the SSAO calculations. Default value is 8
  73937. */
  73938. _this._samples = 8;
  73939. /**
  73940. * Are we using bilateral blur ?
  73941. */
  73942. _this._expensiveBlur = true;
  73943. /**
  73944. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73945. */
  73946. _this.radius = 2.0;
  73947. /**
  73948. * The base color of the SSAO post-process
  73949. * The final result is "base + ssao" between [0, 1]
  73950. */
  73951. _this.base = 0.1;
  73952. _this._firstUpdate = true;
  73953. _this._scene = scene;
  73954. _this._ratio = ratio;
  73955. if (!_this.isSupported) {
  73956. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73957. return _this;
  73958. }
  73959. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73960. var blurRatio = _this._ratio.blurRatio || ratio;
  73961. // Set up assets
  73962. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73963. _this._createRandomTexture();
  73964. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73965. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73966. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73967. _this._createSSAOPostProcess(1.0);
  73968. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73969. _this._createSSAOCombinePostProcess(blurRatio);
  73970. // Set up pipeline
  73971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73976. // Finish
  73977. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73978. if (cameras)
  73979. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73980. return _this;
  73981. }
  73982. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73983. get: function () {
  73984. return this._samples;
  73985. },
  73986. set: function (n) {
  73987. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73988. this._samples = n;
  73989. this._sampleSphere = this._generateHemisphere();
  73990. this._firstUpdate = true;
  73991. },
  73992. enumerable: true,
  73993. configurable: true
  73994. });
  73995. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73996. get: function () {
  73997. return this._expensiveBlur;
  73998. },
  73999. set: function (b) {
  74000. 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"]);
  74001. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74002. this._expensiveBlur = b;
  74003. this._firstUpdate = true;
  74004. },
  74005. enumerable: true,
  74006. configurable: true
  74007. });
  74008. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74009. /**
  74010. * Support test.
  74011. */
  74012. get: function () {
  74013. var engine = BABYLON.Engine.LastCreatedEngine;
  74014. if (!engine) {
  74015. return false;
  74016. }
  74017. return engine.getCaps().drawBuffersExtension;
  74018. },
  74019. enumerable: true,
  74020. configurable: true
  74021. });
  74022. // Public Methods
  74023. /**
  74024. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74025. */
  74026. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74027. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74028. for (var i = 0; i < this._scene.cameras.length; i++) {
  74029. var camera = this._scene.cameras[i];
  74030. this._originalColorPostProcess.dispose(camera);
  74031. this._ssaoPostProcess.dispose(camera);
  74032. this._blurHPostProcess.dispose(camera);
  74033. this._blurVPostProcess.dispose(camera);
  74034. this._ssaoCombinePostProcess.dispose(camera);
  74035. }
  74036. this._randomTexture.dispose();
  74037. if (disableGeometryBufferRenderer)
  74038. this._scene.disableGeometryBufferRenderer();
  74039. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74040. _super.prototype.dispose.call(this);
  74041. };
  74042. // Private Methods
  74043. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74044. var _this = this;
  74045. this._samplerOffsets = [];
  74046. var expensive = this.expensiveBlur;
  74047. for (var i = -8; i < 8; i++) {
  74048. this._samplerOffsets.push(i * 2 + 0.5);
  74049. }
  74050. 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");
  74051. this._blurHPostProcess.onApply = function (effect) {
  74052. if (!_this._scene.activeCamera) {
  74053. return;
  74054. }
  74055. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74056. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74057. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74058. effect.setFloat("radius", _this.radius);
  74059. effect.setTexture("depthSampler", _this._depthTexture);
  74060. if (_this._firstUpdate) {
  74061. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74062. }
  74063. };
  74064. 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");
  74065. this._blurVPostProcess.onApply = function (effect) {
  74066. if (!_this._scene.activeCamera) {
  74067. return;
  74068. }
  74069. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74070. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74071. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74072. effect.setFloat("radius", _this.radius);
  74073. effect.setTexture("depthSampler", _this._depthTexture);
  74074. if (_this._firstUpdate) {
  74075. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74076. _this._firstUpdate = false;
  74077. }
  74078. };
  74079. };
  74080. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74081. this._firstUpdate = true;
  74082. _super.prototype._rebuild.call(this);
  74083. };
  74084. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74085. var numSamples = this.samples;
  74086. var result = [];
  74087. var vector, scale;
  74088. var rand = function (min, max) {
  74089. return Math.random() * (max - min) + min;
  74090. };
  74091. var i = 0;
  74092. while (i < numSamples) {
  74093. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74094. vector.normalize();
  74095. scale = i / numSamples;
  74096. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74097. vector.scaleInPlace(scale);
  74098. result.push(vector.x, vector.y, vector.z);
  74099. i++;
  74100. }
  74101. return result;
  74102. };
  74103. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74104. var _this = this;
  74105. var numSamples = this.samples;
  74106. this._sampleSphere = this._generateHemisphere();
  74107. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74108. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74109. "base", "range", "projection", "near", "far", "texelSize",
  74110. "xViewport", "yViewport", "maxZ", "minZAspect"
  74111. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74112. this._ssaoPostProcess.onApply = function (effect) {
  74113. if (_this._firstUpdate) {
  74114. effect.setArray3("sampleSphere", _this._sampleSphere);
  74115. effect.setFloat("randTextureTiles", 4.0);
  74116. }
  74117. if (!_this._scene.activeCamera) {
  74118. return;
  74119. }
  74120. effect.setFloat("samplesFactor", 1 / _this.samples);
  74121. effect.setFloat("totalStrength", _this.totalStrength);
  74122. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74123. effect.setFloat("radius", _this.radius);
  74124. effect.setFloat("maxZ", _this.maxZ);
  74125. effect.setFloat("minZAspect", _this.minZAspect);
  74126. effect.setFloat("base", _this.base);
  74127. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74128. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74129. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74130. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74131. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74132. effect.setTexture("textureSampler", _this._depthTexture);
  74133. effect.setTexture("normalSampler", _this._normalTexture);
  74134. effect.setTexture("randomSampler", _this._randomTexture);
  74135. };
  74136. };
  74137. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74138. var _this = this;
  74139. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74140. this._ssaoCombinePostProcess.onApply = function (effect) {
  74141. var viewport = _this._scene.activeCamera.viewport;
  74142. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74143. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74144. };
  74145. };
  74146. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74147. var size = 512;
  74148. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74149. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74150. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74151. var context = this._randomTexture.getContext();
  74152. var rand = function (min, max) {
  74153. return Math.random() * (max - min) + min;
  74154. };
  74155. var randVector = BABYLON.Vector3.Zero();
  74156. for (var x = 0; x < size; x++) {
  74157. for (var y = 0; y < size; y++) {
  74158. randVector.x = rand(0.0, 1.0);
  74159. randVector.y = rand(0.0, 1.0);
  74160. randVector.z = 0.0;
  74161. randVector.normalize();
  74162. randVector.scaleInPlace(255);
  74163. randVector.x = Math.floor(randVector.x);
  74164. randVector.y = Math.floor(randVector.y);
  74165. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74166. context.fillRect(x, y, 1, 1);
  74167. }
  74168. }
  74169. this._randomTexture.update(false);
  74170. };
  74171. /**
  74172. * Serialize the rendering pipeline (Used when exporting)
  74173. * @returns the serialized object
  74174. */
  74175. SSAO2RenderingPipeline.prototype.serialize = function () {
  74176. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74177. serializationObject.customType = "SSAO2RenderingPipeline";
  74178. return serializationObject;
  74179. };
  74180. /**
  74181. * Parse the serialized pipeline
  74182. * @param source Source pipeline.
  74183. * @param scene The scene to load the pipeline to.
  74184. * @param rootUrl The URL of the serialized pipeline.
  74185. * @returns An instantiated pipeline from the serialized object.
  74186. */
  74187. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74188. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74189. };
  74190. __decorate([
  74191. BABYLON.serialize()
  74192. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74193. __decorate([
  74194. BABYLON.serialize()
  74195. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74196. __decorate([
  74197. BABYLON.serialize()
  74198. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74199. __decorate([
  74200. BABYLON.serialize("samples")
  74201. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74202. __decorate([
  74203. BABYLON.serialize()
  74204. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74205. __decorate([
  74206. BABYLON.serialize("expensiveBlur")
  74207. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74208. __decorate([
  74209. BABYLON.serialize()
  74210. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74211. __decorate([
  74212. BABYLON.serialize()
  74213. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74214. return SSAO2RenderingPipeline;
  74215. }(BABYLON.PostProcessRenderPipeline));
  74216. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74217. })(BABYLON || (BABYLON = {}));
  74218. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74219. // BABYLON.JS Chromatic Aberration GLSL Shader
  74220. // Author: Olivier Guyot
  74221. // Separates very slightly R, G and B colors on the edges of the screen
  74222. // Inspired by Francois Tarlier & Martins Upitis
  74223. var BABYLON;
  74224. (function (BABYLON) {
  74225. var LensRenderingPipeline = /** @class */ (function (_super) {
  74226. __extends(LensRenderingPipeline, _super);
  74227. /**
  74228. * @constructor
  74229. *
  74230. * Effect parameters are as follow:
  74231. * {
  74232. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74233. * edge_blur: number; // from 0 to x (1 for realism)
  74234. * distortion: number; // from 0 to x (1 for realism)
  74235. * grain_amount: number; // from 0 to 1
  74236. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74237. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74238. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74239. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74240. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74241. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74242. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74243. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74244. * }
  74245. * Note: if an effect parameter is unset, effect is disabled
  74246. *
  74247. * @param {string} name - The rendering pipeline name
  74248. * @param {object} parameters - An object containing all parameters (see above)
  74249. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74250. * @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)
  74251. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74252. */
  74253. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74254. if (ratio === void 0) { ratio = 1.0; }
  74255. var _this = _super.call(this, scene.getEngine(), name) || this;
  74256. // Lens effects can be of the following:
  74257. // - chromatic aberration (slight shift of RGB colors)
  74258. // - blur on the edge of the lens
  74259. // - lens distortion
  74260. // - depth-of-field blur & highlights enhancing
  74261. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74262. // - grain effect (noise or custom texture)
  74263. // Two additional texture samplers are needed:
  74264. // - depth map (for depth-of-field)
  74265. // - grain texture
  74266. /**
  74267. * The chromatic aberration PostProcess id in the pipeline
  74268. */
  74269. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74270. /**
  74271. * The highlights enhancing PostProcess id in the pipeline
  74272. */
  74273. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74274. /**
  74275. * The depth-of-field PostProcess id in the pipeline
  74276. */
  74277. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74278. _this._scene = scene;
  74279. // Fetch texture samplers
  74280. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74281. if (parameters.grain_texture) {
  74282. _this._grainTexture = parameters.grain_texture;
  74283. }
  74284. else {
  74285. _this._createGrainTexture();
  74286. }
  74287. // save parameters
  74288. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74289. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74290. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74291. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74292. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74293. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74294. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74295. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74296. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74297. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74298. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74299. // Create effects
  74300. _this._createChromaticAberrationPostProcess(ratio);
  74301. _this._createHighlightsPostProcess(ratio);
  74302. _this._createDepthOfFieldPostProcess(ratio / 4);
  74303. // Set up pipeline
  74304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74305. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74306. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74307. if (_this._highlightsGain === -1) {
  74308. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74309. }
  74310. // Finish
  74311. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74312. if (cameras) {
  74313. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74314. }
  74315. return _this;
  74316. }
  74317. // public methods (self explanatory)
  74318. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74319. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74320. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74321. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74322. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74323. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74324. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74325. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74326. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74327. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74328. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74329. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74330. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74331. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74332. };
  74333. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74334. this._highlightsPostProcess.updateEffect();
  74335. };
  74336. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74337. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74338. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74339. this._highlightsGain = amount;
  74340. };
  74341. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74342. if (this._highlightsGain === -1) {
  74343. this._highlightsGain = 1.0;
  74344. }
  74345. this._highlightsThreshold = amount;
  74346. };
  74347. LensRenderingPipeline.prototype.disableHighlights = function () {
  74348. this._highlightsGain = -1;
  74349. };
  74350. /**
  74351. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74352. */
  74353. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74354. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74355. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74356. this._chromaticAberrationPostProcess = null;
  74357. this._highlightsPostProcess = null;
  74358. this._depthOfFieldPostProcess = null;
  74359. this._grainTexture.dispose();
  74360. if (disableDepthRender)
  74361. this._scene.disableDepthRenderer();
  74362. };
  74363. // colors shifting and distortion
  74364. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74365. var _this = this;
  74366. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74367. [], // samplers
  74368. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74369. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74370. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74371. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74372. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74373. effect.setFloat('radialIntensity', 1);
  74374. effect.setFloat2('direction', 17, 17);
  74375. effect.setFloat2('centerPosition', 0.5, 0.5);
  74376. };
  74377. };
  74378. // highlights enhancing
  74379. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74380. var _this = this;
  74381. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74382. [], // samplers
  74383. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74384. this._highlightsPostProcess.onApply = function (effect) {
  74385. effect.setFloat('gain', _this._highlightsGain);
  74386. effect.setFloat('threshold', _this._highlightsThreshold);
  74387. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74388. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74389. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74390. };
  74391. };
  74392. // colors shifting and distortion
  74393. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74394. var _this = this;
  74395. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74396. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74397. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74398. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74399. this._depthOfFieldPostProcess.onApply = function (effect) {
  74400. effect.setTexture("depthSampler", _this._depthTexture);
  74401. effect.setTexture("grainSampler", _this._grainTexture);
  74402. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74403. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74404. effect.setFloat('grain_amount', _this._grainAmount);
  74405. effect.setBool('blur_noise', _this._blurNoise);
  74406. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74407. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74408. effect.setFloat('distortion', _this._distortion);
  74409. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74410. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74411. effect.setFloat('aperture', _this._dofAperture);
  74412. effect.setFloat('darken', _this._dofDarken);
  74413. effect.setFloat('edge_blur', _this._edgeBlur);
  74414. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74415. if (_this._scene.activeCamera) {
  74416. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74417. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74418. }
  74419. };
  74420. };
  74421. // creates a black and white random noise texture, 512x512
  74422. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74423. var size = 512;
  74424. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74425. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74426. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74427. var context = this._grainTexture.getContext();
  74428. var rand = function (min, max) {
  74429. return Math.random() * (max - min) + min;
  74430. };
  74431. var value;
  74432. for (var x = 0; x < size; x++) {
  74433. for (var y = 0; y < size; y++) {
  74434. value = Math.floor(rand(0.42, 0.58) * 255);
  74435. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74436. context.fillRect(x, y, 1, 1);
  74437. }
  74438. }
  74439. this._grainTexture.update(false);
  74440. };
  74441. return LensRenderingPipeline;
  74442. }(BABYLON.PostProcessRenderPipeline));
  74443. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74444. })(BABYLON || (BABYLON = {}));
  74445. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74446. var BABYLON;
  74447. (function (BABYLON) {
  74448. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74449. __extends(StandardRenderingPipeline, _super);
  74450. /**
  74451. * @constructor
  74452. * @param {string} name - The rendering pipeline name
  74453. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74454. * @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)
  74455. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74456. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74457. */
  74458. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74459. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74460. var _this = _super.call(this, scene.getEngine(), name) || this;
  74461. _this.downSampleX4PostProcess = null;
  74462. _this.brightPassPostProcess = null;
  74463. _this.blurHPostProcesses = [];
  74464. _this.blurVPostProcesses = [];
  74465. _this.textureAdderPostProcess = null;
  74466. _this.volumetricLightPostProcess = null;
  74467. _this.volumetricLightSmoothXPostProcess = null;
  74468. _this.volumetricLightSmoothYPostProcess = null;
  74469. _this.volumetricLightMergePostProces = null;
  74470. _this.volumetricLightFinalPostProcess = null;
  74471. _this.luminancePostProcess = null;
  74472. _this.luminanceDownSamplePostProcesses = [];
  74473. _this.hdrPostProcess = null;
  74474. _this.textureAdderFinalPostProcess = null;
  74475. _this.lensFlareFinalPostProcess = null;
  74476. _this.hdrFinalPostProcess = null;
  74477. _this.lensFlarePostProcess = null;
  74478. _this.lensFlareComposePostProcess = null;
  74479. _this.motionBlurPostProcess = null;
  74480. _this.depthOfFieldPostProcess = null;
  74481. // Values
  74482. _this.brightThreshold = 1.0;
  74483. _this.blurWidth = 512.0;
  74484. _this.horizontalBlur = false;
  74485. _this.exposure = 1.0;
  74486. _this.lensTexture = null;
  74487. _this.volumetricLightCoefficient = 0.2;
  74488. _this.volumetricLightPower = 4.0;
  74489. _this.volumetricLightBlurScale = 64.0;
  74490. _this.sourceLight = null;
  74491. _this.hdrMinimumLuminance = 1.0;
  74492. _this.hdrDecreaseRate = 0.5;
  74493. _this.hdrIncreaseRate = 0.5;
  74494. _this.lensColorTexture = null;
  74495. _this.lensFlareStrength = 20.0;
  74496. _this.lensFlareGhostDispersal = 1.4;
  74497. _this.lensFlareHaloWidth = 0.7;
  74498. _this.lensFlareDistortionStrength = 16.0;
  74499. _this.lensStarTexture = null;
  74500. _this.lensFlareDirtTexture = null;
  74501. _this.depthOfFieldDistance = 10.0;
  74502. _this.depthOfFieldBlurWidth = 64.0;
  74503. _this.motionStrength = 1.0;
  74504. // IAnimatable
  74505. _this.animations = [];
  74506. _this._currentDepthOfFieldSource = null;
  74507. _this._hdrCurrentLuminance = 1.0;
  74508. // Getters and setters
  74509. _this._bloomEnabled = true;
  74510. _this._depthOfFieldEnabled = false;
  74511. _this._vlsEnabled = false;
  74512. _this._lensFlareEnabled = false;
  74513. _this._hdrEnabled = false;
  74514. _this._motionBlurEnabled = false;
  74515. _this._motionBlurSamples = 64.0;
  74516. _this._volumetricLightStepsCount = 50.0;
  74517. _this._cameras = cameras || [];
  74518. // Initialize
  74519. _this._scene = scene;
  74520. _this._basePostProcess = originalPostProcess;
  74521. _this._ratio = ratio;
  74522. // Misc
  74523. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74524. // Finish
  74525. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74526. _this._buildPipeline();
  74527. return _this;
  74528. }
  74529. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74530. get: function () {
  74531. return this._bloomEnabled;
  74532. },
  74533. set: function (enabled) {
  74534. if (this._bloomEnabled === enabled) {
  74535. return;
  74536. }
  74537. this._bloomEnabled = enabled;
  74538. this._buildPipeline();
  74539. },
  74540. enumerable: true,
  74541. configurable: true
  74542. });
  74543. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74544. get: function () {
  74545. return this._depthOfFieldEnabled;
  74546. },
  74547. set: function (enabled) {
  74548. if (this._depthOfFieldEnabled === enabled) {
  74549. return;
  74550. }
  74551. this._depthOfFieldEnabled = enabled;
  74552. this._buildPipeline();
  74553. },
  74554. enumerable: true,
  74555. configurable: true
  74556. });
  74557. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74558. get: function () {
  74559. return this._lensFlareEnabled;
  74560. },
  74561. set: function (enabled) {
  74562. if (this._lensFlareEnabled === enabled) {
  74563. return;
  74564. }
  74565. this._lensFlareEnabled = enabled;
  74566. this._buildPipeline();
  74567. },
  74568. enumerable: true,
  74569. configurable: true
  74570. });
  74571. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74572. get: function () {
  74573. return this._hdrEnabled;
  74574. },
  74575. set: function (enabled) {
  74576. if (this._hdrEnabled === enabled) {
  74577. return;
  74578. }
  74579. this._hdrEnabled = enabled;
  74580. this._buildPipeline();
  74581. },
  74582. enumerable: true,
  74583. configurable: true
  74584. });
  74585. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74586. get: function () {
  74587. return this._vlsEnabled;
  74588. },
  74589. set: function (enabled) {
  74590. if (this._vlsEnabled === enabled) {
  74591. return;
  74592. }
  74593. if (enabled) {
  74594. var geometry = this._scene.enableGeometryBufferRenderer();
  74595. if (!geometry) {
  74596. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74597. return;
  74598. }
  74599. }
  74600. this._vlsEnabled = enabled;
  74601. this._buildPipeline();
  74602. },
  74603. enumerable: true,
  74604. configurable: true
  74605. });
  74606. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74607. get: function () {
  74608. return this._motionBlurEnabled;
  74609. },
  74610. set: function (enabled) {
  74611. if (this._motionBlurEnabled === enabled) {
  74612. return;
  74613. }
  74614. this._motionBlurEnabled = enabled;
  74615. this._buildPipeline();
  74616. },
  74617. enumerable: true,
  74618. configurable: true
  74619. });
  74620. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74621. get: function () {
  74622. return this._volumetricLightStepsCount;
  74623. },
  74624. set: function (count) {
  74625. if (this.volumetricLightPostProcess) {
  74626. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74627. }
  74628. this._volumetricLightStepsCount = count;
  74629. },
  74630. enumerable: true,
  74631. configurable: true
  74632. });
  74633. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74634. get: function () {
  74635. return this._motionBlurSamples;
  74636. },
  74637. set: function (samples) {
  74638. if (this.motionBlurPostProcess) {
  74639. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74640. }
  74641. this._motionBlurSamples = samples;
  74642. },
  74643. enumerable: true,
  74644. configurable: true
  74645. });
  74646. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74647. var _this = this;
  74648. var ratio = this._ratio;
  74649. var scene = this._scene;
  74650. this._disposePostProcesses();
  74651. this._reset();
  74652. // Create pass post-process
  74653. if (!this._basePostProcess) {
  74654. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74655. this.originalPostProcess.onApply = function (effect) {
  74656. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74657. };
  74658. }
  74659. else {
  74660. this.originalPostProcess = this._basePostProcess;
  74661. }
  74662. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74663. this._currentDepthOfFieldSource = this.originalPostProcess;
  74664. if (this._bloomEnabled) {
  74665. // Create down sample X4 post-process
  74666. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74667. // Create bright pass post-process
  74668. this._createBrightPassPostProcess(scene, ratio / 2);
  74669. // Create gaussian blur post-processes (down sampling blurs)
  74670. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74671. // Create texture adder post-process
  74672. this._createTextureAdderPostProcess(scene, ratio);
  74673. // Create depth-of-field source post-process
  74674. 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);
  74675. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74676. }
  74677. if (this._vlsEnabled) {
  74678. // Create volumetric light
  74679. this._createVolumetricLightPostProcess(scene, ratio);
  74680. // Create volumetric light final post-process
  74681. 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);
  74682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74683. }
  74684. if (this._lensFlareEnabled) {
  74685. // Create lens flare post-process
  74686. this._createLensFlarePostProcess(scene, ratio);
  74687. // Create depth-of-field source post-process post lens-flare and disable it now
  74688. 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);
  74689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74690. }
  74691. if (this._hdrEnabled) {
  74692. // Create luminance
  74693. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74694. // Create HDR
  74695. this._createHdrPostProcess(scene, ratio);
  74696. // Create depth-of-field source post-process post hdr and disable it now
  74697. 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);
  74698. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74699. }
  74700. if (this._depthOfFieldEnabled) {
  74701. // Create gaussian blur used by depth-of-field
  74702. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74703. // Create depth-of-field post-process
  74704. this._createDepthOfFieldPostProcess(scene, ratio);
  74705. }
  74706. if (this._motionBlurEnabled) {
  74707. // Create motion blur post-process
  74708. this._createMotionBlurPostProcess(scene, ratio);
  74709. }
  74710. if (this._cameras !== null) {
  74711. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74712. }
  74713. };
  74714. // Down Sample X4 Post-Processs
  74715. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74716. var _this = this;
  74717. var downSampleX4Offsets = new Array(32);
  74718. 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);
  74719. this.downSampleX4PostProcess.onApply = function (effect) {
  74720. var id = 0;
  74721. var width = _this.downSampleX4PostProcess.width;
  74722. var height = _this.downSampleX4PostProcess.height;
  74723. for (var i = -2; i < 2; i++) {
  74724. for (var j = -2; j < 2; j++) {
  74725. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74726. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74727. id += 2;
  74728. }
  74729. }
  74730. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74731. };
  74732. // Add to pipeline
  74733. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74734. };
  74735. // Brightpass Post-Process
  74736. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74737. var _this = this;
  74738. var brightOffsets = new Array(8);
  74739. 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);
  74740. this.brightPassPostProcess.onApply = function (effect) {
  74741. var sU = (1.0 / _this.brightPassPostProcess.width);
  74742. var sV = (1.0 / _this.brightPassPostProcess.height);
  74743. brightOffsets[0] = -0.5 * sU;
  74744. brightOffsets[1] = 0.5 * sV;
  74745. brightOffsets[2] = 0.5 * sU;
  74746. brightOffsets[3] = 0.5 * sV;
  74747. brightOffsets[4] = -0.5 * sU;
  74748. brightOffsets[5] = -0.5 * sV;
  74749. brightOffsets[6] = 0.5 * sU;
  74750. brightOffsets[7] = -0.5 * sV;
  74751. effect.setArray2("dsOffsets", brightOffsets);
  74752. effect.setFloat("brightThreshold", _this.brightThreshold);
  74753. };
  74754. // Add to pipeline
  74755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74756. };
  74757. // Create blur H&V post-processes
  74758. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74759. var _this = this;
  74760. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74761. var engine = scene.getEngine();
  74762. 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);
  74763. 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);
  74764. blurX.onActivateObservable.add(function () {
  74765. var dw = blurX.width / engine.getRenderWidth();
  74766. blurX.kernel = _this[blurWidthKey] * dw;
  74767. });
  74768. blurY.onActivateObservable.add(function () {
  74769. var dw = blurY.height / engine.getRenderHeight();
  74770. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74771. });
  74772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74774. this.blurHPostProcesses.push(blurX);
  74775. this.blurVPostProcesses.push(blurY);
  74776. };
  74777. // Create texture adder post-process
  74778. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74779. var _this = this;
  74780. 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);
  74781. this.textureAdderPostProcess.onApply = function (effect) {
  74782. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74783. effect.setTexture("lensSampler", _this.lensTexture);
  74784. effect.setFloat("exposure", _this.exposure);
  74785. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74786. };
  74787. // Add to pipeline
  74788. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74789. };
  74790. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74791. var _this = this;
  74792. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74793. geometryRenderer.enablePosition = true;
  74794. var geometry = geometryRenderer.getGBuffer();
  74795. // Base post-process
  74796. 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));
  74797. var depthValues = BABYLON.Vector2.Zero();
  74798. this.volumetricLightPostProcess.onApply = function (effect) {
  74799. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74800. var generator = _this.sourceLight.getShadowGenerator();
  74801. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74802. effect.setTexture("positionSampler", geometry.textures[2]);
  74803. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74804. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74805. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74806. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74807. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74808. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74809. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74810. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74811. effect.setVector2("depthValues", depthValues);
  74812. }
  74813. };
  74814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74815. // Smooth
  74816. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74817. // Merge
  74818. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74819. this.volumetricLightMergePostProces.onApply = function (effect) {
  74820. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74821. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74822. };
  74823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74824. };
  74825. // Create luminance
  74826. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74827. var _this = this;
  74828. // Create luminance
  74829. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74830. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74831. var offsets = [];
  74832. this.luminancePostProcess.onApply = function (effect) {
  74833. var sU = (1.0 / _this.luminancePostProcess.width);
  74834. var sV = (1.0 / _this.luminancePostProcess.height);
  74835. offsets[0] = -0.5 * sU;
  74836. offsets[1] = 0.5 * sV;
  74837. offsets[2] = 0.5 * sU;
  74838. offsets[3] = 0.5 * sV;
  74839. offsets[4] = -0.5 * sU;
  74840. offsets[5] = -0.5 * sV;
  74841. offsets[6] = 0.5 * sU;
  74842. offsets[7] = -0.5 * sV;
  74843. effect.setArray2("lumOffsets", offsets);
  74844. };
  74845. // Add to pipeline
  74846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74847. // Create down sample luminance
  74848. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74849. var size = Math.pow(3, i);
  74850. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74851. if (i === 0) {
  74852. defines += "#define FINAL_DOWN_SAMPLER";
  74853. }
  74854. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74855. this.luminanceDownSamplePostProcesses.push(postProcess);
  74856. }
  74857. // Create callbacks and add effects
  74858. var lastLuminance = this.luminancePostProcess;
  74859. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74860. var downSampleOffsets = new Array(18);
  74861. pp.onApply = function (effect) {
  74862. if (!lastLuminance) {
  74863. return;
  74864. }
  74865. var id = 0;
  74866. for (var x = -1; x < 2; x++) {
  74867. for (var y = -1; y < 2; y++) {
  74868. downSampleOffsets[id] = x / lastLuminance.width;
  74869. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74870. id += 2;
  74871. }
  74872. }
  74873. effect.setArray2("dsOffsets", downSampleOffsets);
  74874. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74875. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74876. lastLuminance = _this.luminancePostProcess;
  74877. }
  74878. else {
  74879. lastLuminance = pp;
  74880. }
  74881. };
  74882. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74883. pp.onAfterRender = function (effect) {
  74884. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74885. 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);
  74886. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74887. };
  74888. }
  74889. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74890. });
  74891. };
  74892. // Create HDR post-process
  74893. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74894. var _this = this;
  74895. 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);
  74896. var outputLiminance = 1;
  74897. var time = 0;
  74898. var lastTime = 0;
  74899. this.hdrPostProcess.onApply = function (effect) {
  74900. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74901. time += scene.getEngine().getDeltaTime();
  74902. if (outputLiminance < 0) {
  74903. outputLiminance = _this._hdrCurrentLuminance;
  74904. }
  74905. else {
  74906. var dt = (lastTime - time) / 1000.0;
  74907. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74908. outputLiminance += _this.hdrDecreaseRate * dt;
  74909. }
  74910. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74911. outputLiminance -= _this.hdrIncreaseRate * dt;
  74912. }
  74913. else {
  74914. outputLiminance = _this._hdrCurrentLuminance;
  74915. }
  74916. }
  74917. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74918. effect.setFloat("averageLuminance", outputLiminance);
  74919. lastTime = time;
  74920. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74921. };
  74922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74923. };
  74924. // Create lens flare post-process
  74925. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74926. var _this = this;
  74927. 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);
  74928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74929. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74930. 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);
  74931. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74932. var resolution = new BABYLON.Vector2(0, 0);
  74933. // Lens flare
  74934. this.lensFlarePostProcess.onApply = function (effect) {
  74935. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74936. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74937. effect.setFloat("strength", _this.lensFlareStrength);
  74938. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74939. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74940. // Shift
  74941. resolution.x = _this.lensFlarePostProcess.width;
  74942. resolution.y = _this.lensFlarePostProcess.height;
  74943. effect.setVector2("resolution", resolution);
  74944. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74945. };
  74946. // Compose
  74947. 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);
  74948. 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);
  74949. this.lensFlareComposePostProcess.onApply = function (effect) {
  74950. if (!_this._scene.activeCamera) {
  74951. return;
  74952. }
  74953. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74954. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74955. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74956. // Lens start rotation matrix
  74957. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74958. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74959. 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));
  74960. camRot *= 4.0;
  74961. 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);
  74962. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74963. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74964. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74965. };
  74966. };
  74967. // Create depth-of-field post-process
  74968. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74969. var _this = this;
  74970. 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);
  74971. this.depthOfFieldPostProcess.onApply = function (effect) {
  74972. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74973. effect.setTexture("depthSampler", _this._getDepthTexture());
  74974. effect.setFloat("distance", _this.depthOfFieldDistance);
  74975. };
  74976. // Add to pipeline
  74977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74978. };
  74979. // Create motion blur post-process
  74980. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74981. var _this = this;
  74982. 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);
  74983. var motionScale = 0;
  74984. var prevViewProjection = BABYLON.Matrix.Identity();
  74985. var invViewProjection = BABYLON.Matrix.Identity();
  74986. var viewProjection = BABYLON.Matrix.Identity();
  74987. var screenSize = BABYLON.Vector2.Zero();
  74988. this.motionBlurPostProcess.onApply = function (effect) {
  74989. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74990. viewProjection.invertToRef(invViewProjection);
  74991. effect.setMatrix("inverseViewProjection", invViewProjection);
  74992. effect.setMatrix("prevViewProjection", prevViewProjection);
  74993. prevViewProjection = viewProjection;
  74994. screenSize.x = _this.motionBlurPostProcess.width;
  74995. screenSize.y = _this.motionBlurPostProcess.height;
  74996. effect.setVector2("screenSize", screenSize);
  74997. motionScale = scene.getEngine().getFps() / 60.0;
  74998. effect.setFloat("motionScale", motionScale);
  74999. effect.setFloat("motionStrength", _this.motionStrength);
  75000. effect.setTexture("depthSampler", _this._getDepthTexture());
  75001. };
  75002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75003. };
  75004. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75005. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75006. var renderer = this._scene.enableGeometryBufferRenderer();
  75007. return renderer.getGBuffer().textures[0];
  75008. }
  75009. return this._scene.enableDepthRenderer().getDepthMap();
  75010. };
  75011. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75012. for (var i = 0; i < this._cameras.length; i++) {
  75013. var camera = this._cameras[i];
  75014. if (this.originalPostProcess) {
  75015. this.originalPostProcess.dispose(camera);
  75016. }
  75017. if (this.downSampleX4PostProcess) {
  75018. this.downSampleX4PostProcess.dispose(camera);
  75019. }
  75020. if (this.brightPassPostProcess) {
  75021. this.brightPassPostProcess.dispose(camera);
  75022. }
  75023. if (this.textureAdderPostProcess) {
  75024. this.textureAdderPostProcess.dispose(camera);
  75025. }
  75026. if (this.textureAdderFinalPostProcess) {
  75027. this.textureAdderFinalPostProcess.dispose(camera);
  75028. }
  75029. if (this.volumetricLightPostProcess) {
  75030. this.volumetricLightPostProcess.dispose(camera);
  75031. }
  75032. if (this.volumetricLightSmoothXPostProcess) {
  75033. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75034. }
  75035. if (this.volumetricLightSmoothYPostProcess) {
  75036. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75037. }
  75038. if (this.volumetricLightMergePostProces) {
  75039. this.volumetricLightMergePostProces.dispose(camera);
  75040. }
  75041. if (this.volumetricLightFinalPostProcess) {
  75042. this.volumetricLightFinalPostProcess.dispose(camera);
  75043. }
  75044. if (this.lensFlarePostProcess) {
  75045. this.lensFlarePostProcess.dispose(camera);
  75046. }
  75047. if (this.lensFlareComposePostProcess) {
  75048. this.lensFlareComposePostProcess.dispose(camera);
  75049. }
  75050. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75051. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75052. }
  75053. if (this.luminancePostProcess) {
  75054. this.luminancePostProcess.dispose(camera);
  75055. }
  75056. if (this.hdrPostProcess) {
  75057. this.hdrPostProcess.dispose(camera);
  75058. }
  75059. if (this.hdrFinalPostProcess) {
  75060. this.hdrFinalPostProcess.dispose(camera);
  75061. }
  75062. if (this.depthOfFieldPostProcess) {
  75063. this.depthOfFieldPostProcess.dispose(camera);
  75064. }
  75065. if (this.motionBlurPostProcess) {
  75066. this.motionBlurPostProcess.dispose(camera);
  75067. }
  75068. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75069. this.blurHPostProcesses[j].dispose(camera);
  75070. }
  75071. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75072. this.blurVPostProcesses[j].dispose(camera);
  75073. }
  75074. }
  75075. this.originalPostProcess = null;
  75076. this.downSampleX4PostProcess = null;
  75077. this.brightPassPostProcess = null;
  75078. this.textureAdderPostProcess = null;
  75079. this.textureAdderFinalPostProcess = null;
  75080. this.volumetricLightPostProcess = null;
  75081. this.volumetricLightSmoothXPostProcess = null;
  75082. this.volumetricLightSmoothYPostProcess = null;
  75083. this.volumetricLightMergePostProces = null;
  75084. this.volumetricLightFinalPostProcess = null;
  75085. this.lensFlarePostProcess = null;
  75086. this.lensFlareComposePostProcess = null;
  75087. this.luminancePostProcess = null;
  75088. this.hdrPostProcess = null;
  75089. this.hdrFinalPostProcess = null;
  75090. this.depthOfFieldPostProcess = null;
  75091. this.motionBlurPostProcess = null;
  75092. this.luminanceDownSamplePostProcesses = [];
  75093. this.blurHPostProcesses = [];
  75094. this.blurVPostProcesses = [];
  75095. };
  75096. /**
  75097. * Dispose of the pipeline and stop all post processes
  75098. */
  75099. StandardRenderingPipeline.prototype.dispose = function () {
  75100. this._disposePostProcesses();
  75101. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75102. _super.prototype.dispose.call(this);
  75103. };
  75104. /**
  75105. * Serialize the rendering pipeline (Used when exporting)
  75106. * @returns the serialized object
  75107. */
  75108. StandardRenderingPipeline.prototype.serialize = function () {
  75109. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75110. if (this.sourceLight) {
  75111. serializationObject.sourceLightId = this.sourceLight.id;
  75112. }
  75113. serializationObject.customType = "StandardRenderingPipeline";
  75114. return serializationObject;
  75115. };
  75116. /**
  75117. * Parse the serialized pipeline
  75118. * @param source Source pipeline.
  75119. * @param scene The scene to load the pipeline to.
  75120. * @param rootUrl The URL of the serialized pipeline.
  75121. * @returns An instantiated pipeline from the serialized object.
  75122. */
  75123. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75124. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75125. if (source.sourceLightId) {
  75126. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75127. }
  75128. return p;
  75129. };
  75130. // Luminance steps
  75131. StandardRenderingPipeline.LuminanceSteps = 6;
  75132. __decorate([
  75133. BABYLON.serialize()
  75134. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75135. __decorate([
  75136. BABYLON.serialize()
  75137. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75138. __decorate([
  75139. BABYLON.serialize()
  75140. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75141. __decorate([
  75142. BABYLON.serialize()
  75143. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75144. __decorate([
  75145. BABYLON.serializeAsTexture("lensTexture")
  75146. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75147. __decorate([
  75148. BABYLON.serialize()
  75149. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75150. __decorate([
  75151. BABYLON.serialize()
  75152. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75153. __decorate([
  75154. BABYLON.serialize()
  75155. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75156. __decorate([
  75157. BABYLON.serialize()
  75158. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75159. __decorate([
  75160. BABYLON.serialize()
  75161. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75165. __decorate([
  75166. BABYLON.serializeAsTexture("lensColorTexture")
  75167. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75168. __decorate([
  75169. BABYLON.serialize()
  75170. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75171. __decorate([
  75172. BABYLON.serialize()
  75173. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75174. __decorate([
  75175. BABYLON.serialize()
  75176. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75177. __decorate([
  75178. BABYLON.serialize()
  75179. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75180. __decorate([
  75181. BABYLON.serializeAsTexture("lensStarTexture")
  75182. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75183. __decorate([
  75184. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75185. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75186. __decorate([
  75187. BABYLON.serialize()
  75188. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75195. __decorate([
  75196. BABYLON.serialize()
  75197. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75204. __decorate([
  75205. BABYLON.serialize()
  75206. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75210. __decorate([
  75211. BABYLON.serialize()
  75212. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75213. __decorate([
  75214. BABYLON.serialize()
  75215. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75222. return StandardRenderingPipeline;
  75223. }(BABYLON.PostProcessRenderPipeline));
  75224. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75225. })(BABYLON || (BABYLON = {}));
  75226. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75227. var BABYLON;
  75228. (function (BABYLON) {
  75229. var FxaaPostProcess = /** @class */ (function (_super) {
  75230. __extends(FxaaPostProcess, _super);
  75231. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75232. if (camera === void 0) { camera = null; }
  75233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75234. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75235. var defines = _this._getDefines();
  75236. _this.updateEffect(defines);
  75237. _this.onApplyObservable.add(function (effect) {
  75238. var texelSize = _this.texelSize;
  75239. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75240. });
  75241. return _this;
  75242. }
  75243. FxaaPostProcess.prototype._getDefines = function () {
  75244. var engine = this.getEngine();
  75245. if (!engine) {
  75246. return null;
  75247. }
  75248. var glInfo = engine.getGlInfo();
  75249. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75250. return "#define MALI 1\n";
  75251. }
  75252. return null;
  75253. };
  75254. return FxaaPostProcess;
  75255. }(BABYLON.PostProcess));
  75256. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75257. })(BABYLON || (BABYLON = {}));
  75258. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75259. var BABYLON;
  75260. (function (BABYLON) {
  75261. /**
  75262. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75263. */
  75264. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75265. __extends(ChromaticAberrationPostProcess, _super);
  75266. /**
  75267. * Creates a new instance ChromaticAberrationPostProcess
  75268. * @param name The name of the effect.
  75269. * @param screenWidth The width of the screen to apply the effect on.
  75270. * @param screenHeight The height of the screen to apply the effect on.
  75271. * @param options The required width/height ratio to downsize to before computing the render pass.
  75272. * @param camera The camera to apply the render pass to.
  75273. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75274. * @param engine The engine which the post process will be applied. (default: current engine)
  75275. * @param reusable If the post process can be reused on the same frame. (default: false)
  75276. * @param textureType Type of textures used when performing the post process. (default: 0)
  75277. * @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)
  75278. */
  75279. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75280. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75281. if (blockCompilation === void 0) { blockCompilation = false; }
  75282. 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;
  75283. /**
  75284. * The amount of seperation of rgb channels (default: 30)
  75285. */
  75286. _this.aberrationAmount = 30;
  75287. /**
  75288. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75289. */
  75290. _this.radialIntensity = 0;
  75291. /**
  75292. * 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))
  75293. */
  75294. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75295. /**
  75296. * 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))
  75297. */
  75298. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75299. _this.onApplyObservable.add(function (effect) {
  75300. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75301. effect.setFloat('screen_width', screenWidth);
  75302. effect.setFloat('screen_height', screenHeight);
  75303. effect.setFloat('radialIntensity', _this.radialIntensity);
  75304. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75305. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75306. });
  75307. return _this;
  75308. }
  75309. return ChromaticAberrationPostProcess;
  75310. }(BABYLON.PostProcess));
  75311. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75312. })(BABYLON || (BABYLON = {}));
  75313. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75314. var BABYLON;
  75315. (function (BABYLON) {
  75316. /**
  75317. * The GrainPostProcess adds noise to the image at mid luminance levels
  75318. */
  75319. var GrainPostProcess = /** @class */ (function (_super) {
  75320. __extends(GrainPostProcess, _super);
  75321. /**
  75322. * Creates a new instance of @see GrainPostProcess
  75323. * @param name The name of the effect.
  75324. * @param options The required width/height ratio to downsize to before computing the render pass.
  75325. * @param camera The camera to apply the render pass to.
  75326. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75327. * @param engine The engine which the post process will be applied. (default: current engine)
  75328. * @param reusable If the post process can be reused on the same frame. (default: false)
  75329. * @param textureType Type of textures used when performing the post process. (default: 0)
  75330. * @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)
  75331. */
  75332. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75333. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75334. if (blockCompilation === void 0) { blockCompilation = false; }
  75335. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75336. /**
  75337. * The intensity of the grain added (default: 30)
  75338. */
  75339. _this.intensity = 30;
  75340. /**
  75341. * If the grain should be randomized on every frame
  75342. */
  75343. _this.animated = false;
  75344. _this.onApplyObservable.add(function (effect) {
  75345. effect.setFloat('intensity', _this.intensity);
  75346. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75347. });
  75348. return _this;
  75349. }
  75350. return GrainPostProcess;
  75351. }(BABYLON.PostProcess));
  75352. BABYLON.GrainPostProcess = GrainPostProcess;
  75353. })(BABYLON || (BABYLON = {}));
  75354. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75355. var BABYLON;
  75356. (function (BABYLON) {
  75357. /**
  75358. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75359. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75360. */
  75361. var SharpenPostProcess = /** @class */ (function (_super) {
  75362. __extends(SharpenPostProcess, _super);
  75363. /**
  75364. * Creates a new instance ConvolutionPostProcess
  75365. * @param name The name of the effect.
  75366. * @param options The required width/height ratio to downsize to before computing the render pass.
  75367. * @param camera The camera to apply the render pass to.
  75368. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75369. * @param engine The engine which the post process will be applied. (default: current engine)
  75370. * @param reusable If the post process can be reused on the same frame. (default: false)
  75371. * @param textureType Type of textures used when performing the post process. (default: 0)
  75372. * @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)
  75373. */
  75374. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75376. if (blockCompilation === void 0) { blockCompilation = false; }
  75377. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75378. /**
  75379. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75380. */
  75381. _this.colorAmount = 1.0;
  75382. /**
  75383. * How much sharpness should be applied (default: 0.3)
  75384. */
  75385. _this.edgeAmount = 0.3;
  75386. _this.onApply = function (effect) {
  75387. effect.setFloat2("screenSize", _this.width, _this.height);
  75388. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75389. };
  75390. return _this;
  75391. }
  75392. return SharpenPostProcess;
  75393. }(BABYLON.PostProcess));
  75394. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75395. })(BABYLON || (BABYLON = {}));
  75396. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75397. var BABYLON;
  75398. (function (BABYLON) {
  75399. /**
  75400. * The Blur Post Process which blurs an image based on a kernel and direction.
  75401. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75402. */
  75403. var BlurPostProcess = /** @class */ (function (_super) {
  75404. __extends(BlurPostProcess, _super);
  75405. /**
  75406. * Creates a new instance BlurPostProcess
  75407. * @param name The name of the effect.
  75408. * @param direction The direction in which to blur the image.
  75409. * @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.
  75410. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75411. * @param camera The camera to apply the render pass to.
  75412. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75413. * @param engine The engine which the post process will be applied. (default: current engine)
  75414. * @param reusable If the post process can be reused on the same frame. (default: false)
  75415. * @param textureType Type of textures used when performing the post process. (default: 0)
  75416. * @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)
  75417. */
  75418. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75420. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75421. if (defines === void 0) { defines = ""; }
  75422. if (blockCompilation === void 0) { blockCompilation = false; }
  75423. 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;
  75424. _this.direction = direction;
  75425. _this.blockCompilation = blockCompilation;
  75426. _this._packedFloat = false;
  75427. _this._staticDefines = "";
  75428. _this._staticDefines = defines;
  75429. _this.onApplyObservable.add(function (effect) {
  75430. if (_this._outputTexture) {
  75431. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75432. }
  75433. else {
  75434. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75435. }
  75436. });
  75437. _this.kernel = kernel;
  75438. return _this;
  75439. }
  75440. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75441. /**
  75442. * Gets the length in pixels of the blur sample region
  75443. */
  75444. get: function () {
  75445. return this._idealKernel;
  75446. },
  75447. /**
  75448. * Sets the length in pixels of the blur sample region
  75449. */
  75450. set: function (v) {
  75451. if (this._idealKernel === v) {
  75452. return;
  75453. }
  75454. v = Math.max(v, 1);
  75455. this._idealKernel = v;
  75456. this._kernel = this._nearestBestKernel(v);
  75457. if (!this.blockCompilation) {
  75458. this._updateParameters();
  75459. }
  75460. },
  75461. enumerable: true,
  75462. configurable: true
  75463. });
  75464. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75465. /**
  75466. * Gets wether or not the blur is unpacking/repacking floats
  75467. */
  75468. get: function () {
  75469. return this._packedFloat;
  75470. },
  75471. /**
  75472. * Sets wether or not the blur needs to unpack/repack floats
  75473. */
  75474. set: function (v) {
  75475. if (this._packedFloat === v) {
  75476. return;
  75477. }
  75478. this._packedFloat = v;
  75479. if (!this.blockCompilation) {
  75480. this._updateParameters();
  75481. }
  75482. },
  75483. enumerable: true,
  75484. configurable: true
  75485. });
  75486. /**
  75487. * Updates the effect with the current post process compile time values and recompiles the shader.
  75488. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75489. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75490. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75491. * @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
  75492. * @param onCompiled Called when the shader has been compiled.
  75493. * @param onError Called if there is an error when compiling a shader.
  75494. */
  75495. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75496. if (defines === void 0) { defines = null; }
  75497. if (uniforms === void 0) { uniforms = null; }
  75498. if (samplers === void 0) { samplers = null; }
  75499. this._updateParameters(onCompiled, onError);
  75500. };
  75501. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75502. // Generate sampling offsets and weights
  75503. var N = this._kernel;
  75504. var centerIndex = (N - 1) / 2;
  75505. // Generate Gaussian sampling weights over kernel
  75506. var offsets = [];
  75507. var weights = [];
  75508. var totalWeight = 0;
  75509. for (var i = 0; i < N; i++) {
  75510. var u = i / (N - 1);
  75511. var w = this._gaussianWeight(u * 2.0 - 1);
  75512. offsets[i] = (i - centerIndex);
  75513. weights[i] = w;
  75514. totalWeight += w;
  75515. }
  75516. // Normalize weights
  75517. for (var i = 0; i < weights.length; i++) {
  75518. weights[i] /= totalWeight;
  75519. }
  75520. // Optimize: combine samples to take advantage of hardware linear sampling
  75521. // Walk from left to center, combining pairs (symmetrically)
  75522. var linearSamplingWeights = [];
  75523. var linearSamplingOffsets = [];
  75524. var linearSamplingMap = [];
  75525. for (var i = 0; i <= centerIndex; i += 2) {
  75526. var j = Math.min(i + 1, Math.floor(centerIndex));
  75527. var singleCenterSample = i === j;
  75528. if (singleCenterSample) {
  75529. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75530. }
  75531. else {
  75532. var sharedCell = j === centerIndex;
  75533. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75534. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75535. if (offsetLinear === 0) {
  75536. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75537. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75538. }
  75539. else {
  75540. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75541. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75542. }
  75543. }
  75544. }
  75545. for (var i = 0; i < linearSamplingMap.length; i++) {
  75546. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75547. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75548. }
  75549. // Replace with optimized
  75550. offsets = linearSamplingOffsets;
  75551. weights = linearSamplingWeights;
  75552. // Generate shaders
  75553. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75554. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75555. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75556. var defines = "";
  75557. defines += this._staticDefines;
  75558. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75559. if (this._staticDefines.indexOf("DOF") != -1) {
  75560. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75561. varyingCount--;
  75562. }
  75563. for (var i = 0; i < varyingCount; i++) {
  75564. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75565. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75566. }
  75567. var depCount = 0;
  75568. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75569. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75570. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75571. depCount++;
  75572. }
  75573. if (this.packedFloat) {
  75574. defines += "#define PACKEDFLOAT 1";
  75575. }
  75576. this.blockCompilation = false;
  75577. _super.prototype.updateEffect.call(this, defines, null, null, {
  75578. varyingCount: varyingCount,
  75579. depCount: depCount
  75580. }, onCompiled, onError);
  75581. };
  75582. /**
  75583. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75584. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75585. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75586. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75587. * The gaps between physical kernels are compensated for in the weighting of the samples
  75588. * @param idealKernel Ideal blur kernel.
  75589. * @return Nearest best kernel.
  75590. */
  75591. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75592. var v = Math.round(idealKernel);
  75593. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75594. var k = _a[_i];
  75595. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75596. return Math.max(k, 3);
  75597. }
  75598. }
  75599. return Math.max(v, 3);
  75600. };
  75601. /**
  75602. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75603. * @param x The point on the Gaussian distribution to sample.
  75604. * @return the value of the Gaussian function at x.
  75605. */
  75606. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75607. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75608. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75609. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75610. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75611. // truncated at around 1.3% of peak strength.
  75612. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75613. var sigma = (1 / 3);
  75614. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75615. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75616. var weight = (1.0 / denominator) * Math.exp(exponent);
  75617. return weight;
  75618. };
  75619. /**
  75620. * Generates a string that can be used as a floating point number in GLSL.
  75621. * @param x Value to print.
  75622. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75623. * @return GLSL float string.
  75624. */
  75625. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75626. if (decimalFigures === void 0) { decimalFigures = 8; }
  75627. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75628. };
  75629. return BlurPostProcess;
  75630. }(BABYLON.PostProcess));
  75631. BABYLON.BlurPostProcess = BlurPostProcess;
  75632. })(BABYLON || (BABYLON = {}));
  75633. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75634. var BABYLON;
  75635. (function (BABYLON) {
  75636. /**
  75637. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75638. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75639. * based on samples that have a large difference in distance than the center pixel.
  75640. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75641. */
  75642. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75643. __extends(DepthOfFieldBlurPostProcess, _super);
  75644. /**
  75645. * Creates a new instance CircleOfConfusionPostProcess
  75646. * @param name The name of the effect.
  75647. * @param scene The scene the effect belongs to.
  75648. * @param direction The direction the blur should be applied.
  75649. * @param kernel The size of the kernel used to blur.
  75650. * @param options The required width/height ratio to downsize to before computing the render pass.
  75651. * @param camera The camera to apply the render pass to.
  75652. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75653. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75654. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75655. * @param engine The engine which the post process will be applied. (default: current engine)
  75656. * @param reusable If the post process can be reused on the same frame. (default: false)
  75657. * @param textureType Type of textures used when performing the post process. (default: 0)
  75658. * @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)
  75659. */
  75660. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75661. if (imageToBlur === void 0) { imageToBlur = null; }
  75662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75663. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75664. if (blockCompilation === void 0) { blockCompilation = false; }
  75665. 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;
  75666. _this.direction = direction;
  75667. _this.onApplyObservable.add(function (effect) {
  75668. if (imageToBlur != null) {
  75669. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75670. }
  75671. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75672. if (scene.activeCamera) {
  75673. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75674. }
  75675. });
  75676. return _this;
  75677. }
  75678. return DepthOfFieldBlurPostProcess;
  75679. }(BABYLON.BlurPostProcess));
  75680. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75681. })(BABYLON || (BABYLON = {}));
  75682. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75683. var BABYLON;
  75684. (function (BABYLON) {
  75685. /**
  75686. * Options to be set when merging outputs from the default pipeline.
  75687. */
  75688. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75689. function DepthOfFieldMergePostProcessOptions() {
  75690. }
  75691. return DepthOfFieldMergePostProcessOptions;
  75692. }());
  75693. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75694. /**
  75695. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75696. */
  75697. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75698. __extends(DepthOfFieldMergePostProcess, _super);
  75699. /**
  75700. * Creates a new instance of DepthOfFieldMergePostProcess
  75701. * @param name The name of the effect.
  75702. * @param originalFromInput Post process which's input will be used for the merge.
  75703. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75704. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75705. * @param options The required width/height ratio to downsize to before computing the render pass.
  75706. * @param camera The camera to apply the render pass to.
  75707. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75708. * @param engine The engine which the post process will be applied. (default: current engine)
  75709. * @param reusable If the post process can be reused on the same frame. (default: false)
  75710. * @param textureType Type of textures used when performing the post process. (default: 0)
  75711. * @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)
  75712. */
  75713. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75715. if (blockCompilation === void 0) { blockCompilation = false; }
  75716. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75717. _this.blurSteps = blurSteps;
  75718. _this.onApplyObservable.add(function (effect) {
  75719. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75720. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75721. blurSteps.forEach(function (step, index) {
  75722. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75723. });
  75724. });
  75725. if (!blockCompilation) {
  75726. _this.updateEffect();
  75727. }
  75728. return _this;
  75729. }
  75730. /**
  75731. * Updates the effect with the current post process compile time values and recompiles the shader.
  75732. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75733. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75734. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75735. * @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
  75736. * @param onCompiled Called when the shader has been compiled.
  75737. * @param onError Called if there is an error when compiling a shader.
  75738. */
  75739. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75740. if (defines === void 0) { defines = null; }
  75741. if (uniforms === void 0) { uniforms = null; }
  75742. if (samplers === void 0) { samplers = null; }
  75743. if (!defines) {
  75744. defines = "";
  75745. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75746. }
  75747. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75748. };
  75749. return DepthOfFieldMergePostProcess;
  75750. }(BABYLON.PostProcess));
  75751. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75752. })(BABYLON || (BABYLON = {}));
  75753. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75754. var BABYLON;
  75755. (function (BABYLON) {
  75756. /**
  75757. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75758. */
  75759. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75760. __extends(CircleOfConfusionPostProcess, _super);
  75761. /**
  75762. * Creates a new instance CircleOfConfusionPostProcess
  75763. * @param name The name of the effect.
  75764. * @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.
  75765. * @param options The required width/height ratio to downsize to before computing the render pass.
  75766. * @param camera The camera to apply the render pass to.
  75767. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75768. * @param engine The engine which the post process will be applied. (default: current engine)
  75769. * @param reusable If the post process can be reused on the same frame. (default: false)
  75770. * @param textureType Type of textures used when performing the post process. (default: 0)
  75771. * @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)
  75772. */
  75773. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75774. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75775. if (blockCompilation === void 0) { blockCompilation = false; }
  75776. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75777. /**
  75778. * 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.
  75779. */
  75780. _this.lensSize = 50;
  75781. /**
  75782. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75783. */
  75784. _this.fStop = 1.4;
  75785. /**
  75786. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75787. */
  75788. _this.focusDistance = 2000;
  75789. /**
  75790. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75791. */
  75792. _this.focalLength = 50;
  75793. _this._depthTexture = null;
  75794. _this._depthTexture = depthTexture;
  75795. _this.onApplyObservable.add(function (effect) {
  75796. if (!_this._depthTexture) {
  75797. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75798. return;
  75799. }
  75800. effect.setTexture("depthSampler", _this._depthTexture);
  75801. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75802. var aperture = _this.lensSize / _this.fStop;
  75803. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75804. effect.setFloat('focusDistance', _this.focusDistance);
  75805. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75806. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75807. });
  75808. return _this;
  75809. }
  75810. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75811. /**
  75812. * 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.
  75813. */
  75814. set: function (value) {
  75815. this._depthTexture = value;
  75816. },
  75817. enumerable: true,
  75818. configurable: true
  75819. });
  75820. return CircleOfConfusionPostProcess;
  75821. }(BABYLON.PostProcess));
  75822. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75823. })(BABYLON || (BABYLON = {}));
  75824. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75825. var BABYLON;
  75826. (function (BABYLON) {
  75827. /**
  75828. * Specifies the level of max blur that should be applied when using the depth of field effect
  75829. */
  75830. var DepthOfFieldEffectBlurLevel;
  75831. (function (DepthOfFieldEffectBlurLevel) {
  75832. /**
  75833. * Subtle blur
  75834. */
  75835. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75836. /**
  75837. * Medium blur
  75838. */
  75839. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75840. /**
  75841. * Large blur
  75842. */
  75843. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75844. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75845. ;
  75846. /**
  75847. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75848. */
  75849. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75850. __extends(DepthOfFieldEffect, _super);
  75851. /**
  75852. * Creates a new instance DepthOfFieldEffect
  75853. * @param scene The scene the effect belongs to.
  75854. * @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.
  75855. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75856. * @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)
  75857. */
  75858. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75859. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75860. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75861. if (blockCompilation === void 0) { blockCompilation = false; }
  75862. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75863. return _this._effects;
  75864. }, true) || this;
  75865. /**
  75866. * Internal post processes in depth of field effect
  75867. */
  75868. _this._effects = [];
  75869. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75870. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75871. // 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)
  75872. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75873. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75874. _this._depthOfFieldBlurY = [];
  75875. _this._depthOfFieldBlurX = [];
  75876. var blurCount = 1;
  75877. var kernelSize = 15;
  75878. switch (blurLevel) {
  75879. case DepthOfFieldEffectBlurLevel.High: {
  75880. blurCount = 3;
  75881. kernelSize = 51;
  75882. break;
  75883. }
  75884. case DepthOfFieldEffectBlurLevel.Medium: {
  75885. blurCount = 2;
  75886. kernelSize = 31;
  75887. break;
  75888. }
  75889. default: {
  75890. kernelSize = 15;
  75891. blurCount = 1;
  75892. break;
  75893. }
  75894. }
  75895. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75896. var ratio = 1.0;
  75897. for (var i = 0; i < blurCount; i++) {
  75898. 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);
  75899. blurY.autoClear = false;
  75900. ratio = 0.75 / Math.pow(2, i);
  75901. 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);
  75902. blurX.autoClear = false;
  75903. _this._depthOfFieldBlurY.push(blurY);
  75904. _this._depthOfFieldBlurX.push(blurX);
  75905. }
  75906. // Set all post processes on the effect.
  75907. _this._effects = [_this._circleOfConfusion];
  75908. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75909. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75910. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75911. }
  75912. // Merge blurred images with original image based on circleOfConfusion
  75913. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75914. _this._dofMerge.autoClear = false;
  75915. _this._effects.push(_this._dofMerge);
  75916. return _this;
  75917. }
  75918. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75919. get: function () {
  75920. return this._circleOfConfusion.focalLength;
  75921. },
  75922. /**
  75923. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75924. */
  75925. set: function (value) {
  75926. this._circleOfConfusion.focalLength = value;
  75927. },
  75928. enumerable: true,
  75929. configurable: true
  75930. });
  75931. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75932. get: function () {
  75933. return this._circleOfConfusion.fStop;
  75934. },
  75935. /**
  75936. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75937. */
  75938. set: function (value) {
  75939. this._circleOfConfusion.fStop = value;
  75940. },
  75941. enumerable: true,
  75942. configurable: true
  75943. });
  75944. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75945. get: function () {
  75946. return this._circleOfConfusion.focusDistance;
  75947. },
  75948. /**
  75949. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75950. */
  75951. set: function (value) {
  75952. this._circleOfConfusion.focusDistance = value;
  75953. },
  75954. enumerable: true,
  75955. configurable: true
  75956. });
  75957. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75958. get: function () {
  75959. return this._circleOfConfusion.lensSize;
  75960. },
  75961. /**
  75962. * 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.
  75963. */
  75964. set: function (value) {
  75965. this._circleOfConfusion.lensSize = value;
  75966. },
  75967. enumerable: true,
  75968. configurable: true
  75969. });
  75970. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75971. /**
  75972. * 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.
  75973. */
  75974. set: function (value) {
  75975. this._circleOfConfusion.depthTexture = value;
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. /**
  75981. * Disposes each of the internal effects for a given camera.
  75982. * @param camera The camera to dispose the effect on.
  75983. */
  75984. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75985. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75986. this._effects[effectIndex].dispose(camera);
  75987. }
  75988. };
  75989. /**
  75990. * Internal
  75991. */
  75992. DepthOfFieldEffect.prototype._updateEffects = function () {
  75993. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75994. this._effects[effectIndex].updateEffect();
  75995. }
  75996. };
  75997. /**
  75998. * Internal
  75999. * @returns if all the contained post processes are ready.
  76000. */
  76001. DepthOfFieldEffect.prototype._isReady = function () {
  76002. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76003. if (!this._effects[effectIndex].isReady()) {
  76004. return false;
  76005. }
  76006. }
  76007. return true;
  76008. };
  76009. return DepthOfFieldEffect;
  76010. }(BABYLON.PostProcessRenderEffect));
  76011. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76012. })(BABYLON || (BABYLON = {}));
  76013. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76014. var BABYLON;
  76015. (function (BABYLON) {
  76016. /**
  76017. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76018. */
  76019. var BloomMergePostProcess = /** @class */ (function (_super) {
  76020. __extends(BloomMergePostProcess, _super);
  76021. /**
  76022. * Creates a new instance of @see BloomMergePostProcess
  76023. * @param name The name of the effect.
  76024. * @param originalFromInput Post process which's input will be used for the merge.
  76025. * @param blurred Blurred highlights post process which's output will be used.
  76026. * @param weight Weight of the bloom to be added to the original input.
  76027. * @param options The required width/height ratio to downsize to before computing the render pass.
  76028. * @param camera The camera to apply the render pass to.
  76029. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76030. * @param engine The engine which the post process will be applied. (default: current engine)
  76031. * @param reusable If the post process can be reused on the same frame. (default: false)
  76032. * @param textureType Type of textures used when performing the post process. (default: 0)
  76033. * @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)
  76034. */
  76035. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76036. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76037. if (blockCompilation === void 0) { blockCompilation = false; }
  76038. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76039. _this.weight = weight;
  76040. _this.onApplyObservable.add(function (effect) {
  76041. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76042. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76043. effect.setFloat("bloomWeight", _this.weight);
  76044. });
  76045. if (!blockCompilation) {
  76046. _this.updateEffect();
  76047. }
  76048. return _this;
  76049. }
  76050. return BloomMergePostProcess;
  76051. }(BABYLON.PostProcess));
  76052. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76053. })(BABYLON || (BABYLON = {}));
  76054. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76055. var BABYLON;
  76056. (function (BABYLON) {
  76057. /**
  76058. * 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.
  76059. */
  76060. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76061. __extends(ExtractHighlightsPostProcess, _super);
  76062. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76063. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76064. if (blockCompilation === void 0) { blockCompilation = false; }
  76065. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76066. /**
  76067. * The luminance threshold, pixels below this value will be set to black.
  76068. */
  76069. _this.threshold = 0.9;
  76070. /**
  76071. * Internal
  76072. */
  76073. _this._exposure = 1;
  76074. /**
  76075. * Post process which has the input texture to be used when performing highlight extraction
  76076. */
  76077. _this._inputPostProcess = null;
  76078. _this.onApplyObservable.add(function (effect) {
  76079. if (_this._inputPostProcess) {
  76080. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76081. }
  76082. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76083. effect.setFloat('exposure', _this._exposure);
  76084. });
  76085. return _this;
  76086. }
  76087. return ExtractHighlightsPostProcess;
  76088. }(BABYLON.PostProcess));
  76089. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76090. })(BABYLON || (BABYLON = {}));
  76091. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76092. var BABYLON;
  76093. (function (BABYLON) {
  76094. /**
  76095. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76096. */
  76097. var BloomEffect = /** @class */ (function (_super) {
  76098. __extends(BloomEffect, _super);
  76099. /**
  76100. * Creates a new instance of @see BloomEffect
  76101. * @param scene The scene the effect belongs to.
  76102. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76103. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76104. * @param bloomWeight The the strength of bloom.
  76105. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76106. * @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)
  76107. */
  76108. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76109. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76110. if (blockCompilation === void 0) { blockCompilation = false; }
  76111. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76112. return _this._effects;
  76113. }, true) || this;
  76114. _this.bloomScale = bloomScale;
  76115. /**
  76116. * Internal
  76117. */
  76118. _this._effects = [];
  76119. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76120. _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);
  76121. _this._blurX.alwaysForcePOT = true;
  76122. _this._blurX.autoClear = false;
  76123. _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);
  76124. _this._blurY.alwaysForcePOT = true;
  76125. _this._blurY.autoClear = false;
  76126. _this.kernel = bloomKernel;
  76127. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76128. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76129. _this._merge.autoClear = false;
  76130. _this._effects.push(_this._merge);
  76131. return _this;
  76132. }
  76133. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76134. /**
  76135. * The luminance threshold to find bright areas of the image to bloom.
  76136. */
  76137. get: function () {
  76138. return this._downscale.threshold;
  76139. },
  76140. set: function (value) {
  76141. this._downscale.threshold = value;
  76142. },
  76143. enumerable: true,
  76144. configurable: true
  76145. });
  76146. Object.defineProperty(BloomEffect.prototype, "weight", {
  76147. /**
  76148. * The strength of the bloom.
  76149. */
  76150. get: function () {
  76151. return this._merge.weight;
  76152. },
  76153. set: function (value) {
  76154. this._merge.weight = value;
  76155. },
  76156. enumerable: true,
  76157. configurable: true
  76158. });
  76159. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76160. /**
  76161. * Specifies the size of the bloom blur kernel, relative to the final output size
  76162. */
  76163. get: function () {
  76164. return this._blurX.kernel / this.bloomScale;
  76165. },
  76166. set: function (value) {
  76167. this._blurX.kernel = value * this.bloomScale;
  76168. this._blurY.kernel = value * this.bloomScale;
  76169. },
  76170. enumerable: true,
  76171. configurable: true
  76172. });
  76173. /**
  76174. * Disposes each of the internal effects for a given camera.
  76175. * @param camera The camera to dispose the effect on.
  76176. */
  76177. BloomEffect.prototype.disposeEffects = function (camera) {
  76178. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76179. this._effects[effectIndex].dispose(camera);
  76180. }
  76181. };
  76182. /**
  76183. * Internal
  76184. */
  76185. BloomEffect.prototype._updateEffects = function () {
  76186. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76187. this._effects[effectIndex].updateEffect();
  76188. }
  76189. };
  76190. /**
  76191. * Internal
  76192. * @returns if all the contained post processes are ready.
  76193. */
  76194. BloomEffect.prototype._isReady = function () {
  76195. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76196. if (!this._effects[effectIndex].isReady()) {
  76197. return false;
  76198. }
  76199. }
  76200. return true;
  76201. };
  76202. return BloomEffect;
  76203. }(BABYLON.PostProcessRenderEffect));
  76204. BABYLON.BloomEffect = BloomEffect;
  76205. })(BABYLON || (BABYLON = {}));
  76206. //# sourceMappingURL=babylon.bloomEffect.js.map
  76207. var BABYLON;
  76208. (function (BABYLON) {
  76209. /**
  76210. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76211. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76212. */
  76213. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76214. __extends(DefaultRenderingPipeline, _super);
  76215. /**
  76216. * @constructor
  76217. * @param {string} name - The rendering pipeline name (default: "")
  76218. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76219. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76220. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76221. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76222. */
  76223. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76224. if (name === void 0) { name = ""; }
  76225. if (hdr === void 0) { hdr = true; }
  76226. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76227. if (automaticBuild === void 0) { automaticBuild = true; }
  76228. var _this = _super.call(this, scene.getEngine(), name) || this;
  76229. _this._camerasToBeAttached = [];
  76230. /**
  76231. * ID of the sharpen post process,
  76232. */
  76233. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76234. /**
  76235. * ID of the image processing post process;
  76236. */
  76237. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76238. /**
  76239. * ID of the Fast Approximate Anti-Aliasing post process;
  76240. */
  76241. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76242. /**
  76243. * ID of the chromatic aberration post process,
  76244. */
  76245. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76246. /**
  76247. * ID of the grain post process
  76248. */
  76249. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76250. /**
  76251. * Glow post process which adds a glow to emmisive areas of the image
  76252. */
  76253. _this._glowLayer = null;
  76254. /**
  76255. * Animations which can be used to tweak settings over a period of time
  76256. */
  76257. _this.animations = [];
  76258. _this._imageProcessingConfigurationObserver = null;
  76259. // Values
  76260. _this._sharpenEnabled = false;
  76261. _this._bloomEnabled = false;
  76262. _this._depthOfFieldEnabled = false;
  76263. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76264. _this._fxaaEnabled = false;
  76265. _this._imageProcessingEnabled = true;
  76266. _this._bloomScale = 0.5;
  76267. _this._chromaticAberrationEnabled = false;
  76268. _this._grainEnabled = false;
  76269. _this._buildAllowed = true;
  76270. _this._resizeObserver = null;
  76271. _this._hardwareScaleLevel = 1.0;
  76272. _this._bloomKernel = 64;
  76273. /**
  76274. * Specifies the weight of the bloom in the final rendering
  76275. */
  76276. _this._bloomWeight = 0.15;
  76277. /**
  76278. * Specifies the luma threshold for the area that will be blurred by the bloom
  76279. */
  76280. _this._bloomThreshold = 0.9;
  76281. _this._samples = 1;
  76282. _this._hasCleared = false;
  76283. _this._prevPostProcess = null;
  76284. _this._prevPrevPostProcess = null;
  76285. _this._cameras = cameras || scene.cameras;
  76286. _this._camerasToBeAttached = _this._cameras.slice();
  76287. _this._buildAllowed = automaticBuild;
  76288. // Initialize
  76289. _this._scene = scene;
  76290. var caps = _this._scene.getEngine().getCaps();
  76291. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76292. // Misc
  76293. if (_this._hdr) {
  76294. if (caps.textureHalfFloatRender) {
  76295. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76296. }
  76297. else if (caps.textureFloatRender) {
  76298. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76299. }
  76300. }
  76301. else {
  76302. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76303. }
  76304. // Attach
  76305. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76306. var engine = _this._scene.getEngine();
  76307. // Create post processes before hand so they can be modified before enabled.
  76308. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76309. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76310. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76311. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76312. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76313. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76314. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76315. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76316. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76317. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76318. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76319. _this.bloomKernel = _this.bloomKernel;
  76320. });
  76321. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76322. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76323. });
  76324. _this._buildPipeline();
  76325. return _this;
  76326. }
  76327. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76328. get: function () {
  76329. return this._sharpenEnabled;
  76330. },
  76331. /**
  76332. * Enable or disable the sharpen process from the pipeline
  76333. */
  76334. set: function (enabled) {
  76335. if (this._sharpenEnabled === enabled) {
  76336. return;
  76337. }
  76338. this._sharpenEnabled = enabled;
  76339. this._buildPipeline();
  76340. },
  76341. enumerable: true,
  76342. configurable: true
  76343. });
  76344. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76345. /**
  76346. * Specifies the size of the bloom blur kernel, relative to the final output size
  76347. */
  76348. get: function () {
  76349. return this._bloomKernel;
  76350. },
  76351. set: function (value) {
  76352. this._bloomKernel = value;
  76353. this.bloom.kernel = value / this._hardwareScaleLevel;
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76359. get: function () {
  76360. return this._bloomWeight;
  76361. },
  76362. /**
  76363. * The strength of the bloom.
  76364. */
  76365. set: function (value) {
  76366. if (this._bloomWeight === value) {
  76367. return;
  76368. }
  76369. this.bloom.weight = value;
  76370. this._bloomWeight = value;
  76371. },
  76372. enumerable: true,
  76373. configurable: true
  76374. });
  76375. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76376. get: function () {
  76377. return this._bloomThreshold;
  76378. },
  76379. /**
  76380. * The strength of the bloom.
  76381. */
  76382. set: function (value) {
  76383. if (this._bloomThreshold === value) {
  76384. return;
  76385. }
  76386. this.bloom.threshold = value;
  76387. this._bloomThreshold = value;
  76388. },
  76389. enumerable: true,
  76390. configurable: true
  76391. });
  76392. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76393. get: function () {
  76394. return this._bloomScale;
  76395. },
  76396. /**
  76397. * The scale of the bloom, lower value will provide better performance.
  76398. */
  76399. set: function (value) {
  76400. if (this._bloomScale === value) {
  76401. return;
  76402. }
  76403. this._bloomScale = value;
  76404. // recreate bloom and dispose old as this setting is not dynamic
  76405. this._rebuildBloom();
  76406. this._buildPipeline();
  76407. },
  76408. enumerable: true,
  76409. configurable: true
  76410. });
  76411. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76412. get: function () {
  76413. return this._bloomEnabled;
  76414. },
  76415. /**
  76416. * Enable or disable the bloom from the pipeline
  76417. */
  76418. set: function (enabled) {
  76419. if (this._bloomEnabled === enabled) {
  76420. return;
  76421. }
  76422. this._bloomEnabled = enabled;
  76423. this._buildPipeline();
  76424. },
  76425. enumerable: true,
  76426. configurable: true
  76427. });
  76428. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76429. // recreate bloom and dispose old as this setting is not dynamic
  76430. var oldBloom = this.bloom;
  76431. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76432. this.bloom.threshold = oldBloom.threshold;
  76433. for (var i = 0; i < this._cameras.length; i++) {
  76434. oldBloom.disposeEffects(this._cameras[i]);
  76435. }
  76436. };
  76437. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76438. /**
  76439. * If the depth of field is enabled.
  76440. */
  76441. get: function () {
  76442. return this._depthOfFieldEnabled;
  76443. },
  76444. set: function (enabled) {
  76445. if (this._depthOfFieldEnabled === enabled) {
  76446. return;
  76447. }
  76448. this._depthOfFieldEnabled = enabled;
  76449. this._buildPipeline();
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76455. /**
  76456. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76457. */
  76458. get: function () {
  76459. return this._depthOfFieldBlurLevel;
  76460. },
  76461. set: function (value) {
  76462. if (this._depthOfFieldBlurLevel === value) {
  76463. return;
  76464. }
  76465. this._depthOfFieldBlurLevel = value;
  76466. // recreate dof and dispose old as this setting is not dynamic
  76467. var oldDof = this.depthOfField;
  76468. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76469. this.depthOfField.focalLength = oldDof.focalLength;
  76470. this.depthOfField.focusDistance = oldDof.focusDistance;
  76471. this.depthOfField.fStop = oldDof.fStop;
  76472. this.depthOfField.lensSize = oldDof.lensSize;
  76473. for (var i = 0; i < this._cameras.length; i++) {
  76474. oldDof.disposeEffects(this._cameras[i]);
  76475. }
  76476. this._buildPipeline();
  76477. },
  76478. enumerable: true,
  76479. configurable: true
  76480. });
  76481. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76482. get: function () {
  76483. return this._fxaaEnabled;
  76484. },
  76485. /**
  76486. * If the anti aliasing is enabled.
  76487. */
  76488. set: function (enabled) {
  76489. if (this._fxaaEnabled === enabled) {
  76490. return;
  76491. }
  76492. this._fxaaEnabled = enabled;
  76493. this._buildPipeline();
  76494. },
  76495. enumerable: true,
  76496. configurable: true
  76497. });
  76498. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76499. get: function () {
  76500. return this._samples;
  76501. },
  76502. /**
  76503. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76504. */
  76505. set: function (sampleCount) {
  76506. if (this._samples === sampleCount) {
  76507. return;
  76508. }
  76509. this._samples = sampleCount;
  76510. this._buildPipeline();
  76511. },
  76512. enumerable: true,
  76513. configurable: true
  76514. });
  76515. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76516. get: function () {
  76517. return this._imageProcessingEnabled;
  76518. },
  76519. /**
  76520. * If image processing is enabled.
  76521. */
  76522. set: function (enabled) {
  76523. if (this._imageProcessingEnabled === enabled) {
  76524. return;
  76525. }
  76526. this._imageProcessingEnabled = enabled;
  76527. this._buildPipeline();
  76528. },
  76529. enumerable: true,
  76530. configurable: true
  76531. });
  76532. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76533. get: function () {
  76534. return this._glowLayer == null;
  76535. },
  76536. /**
  76537. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76538. */
  76539. set: function (enabled) {
  76540. if (enabled && !this._glowLayer) {
  76541. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76542. }
  76543. else if (!enabled && this._glowLayer) {
  76544. this._glowLayer.dispose();
  76545. this._glowLayer = null;
  76546. }
  76547. },
  76548. enumerable: true,
  76549. configurable: true
  76550. });
  76551. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76552. get: function () {
  76553. return this._chromaticAberrationEnabled;
  76554. },
  76555. /**
  76556. * Enable or disable the chromaticAberration process from the pipeline
  76557. */
  76558. set: function (enabled) {
  76559. if (this._chromaticAberrationEnabled === enabled) {
  76560. return;
  76561. }
  76562. this._chromaticAberrationEnabled = enabled;
  76563. this._buildPipeline();
  76564. },
  76565. enumerable: true,
  76566. configurable: true
  76567. });
  76568. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76569. get: function () {
  76570. return this._grainEnabled;
  76571. },
  76572. /**
  76573. * Enable or disable the grain process from the pipeline
  76574. */
  76575. set: function (enabled) {
  76576. if (this._grainEnabled === enabled) {
  76577. return;
  76578. }
  76579. this._grainEnabled = enabled;
  76580. this._buildPipeline();
  76581. },
  76582. enumerable: true,
  76583. configurable: true
  76584. });
  76585. /**
  76586. * Force the compilation of the entire pipeline.
  76587. */
  76588. DefaultRenderingPipeline.prototype.prepare = function () {
  76589. var previousState = this._buildAllowed;
  76590. this._buildAllowed = true;
  76591. this._buildPipeline();
  76592. this._buildAllowed = previousState;
  76593. };
  76594. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76595. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76596. if (this._hasCleared) {
  76597. postProcess.autoClear = false;
  76598. }
  76599. else {
  76600. postProcess.autoClear = true;
  76601. this._scene.autoClear = false;
  76602. this._hasCleared = true;
  76603. }
  76604. if (!skipTextureSharing) {
  76605. if (this._prevPrevPostProcess) {
  76606. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76607. }
  76608. else {
  76609. postProcess.useOwnOutput();
  76610. }
  76611. if (this._prevPostProcess) {
  76612. this._prevPrevPostProcess = this._prevPostProcess;
  76613. }
  76614. this._prevPostProcess = postProcess;
  76615. }
  76616. };
  76617. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76618. var _this = this;
  76619. if (!this._buildAllowed) {
  76620. return;
  76621. }
  76622. this._scene.autoClear = true;
  76623. var engine = this._scene.getEngine();
  76624. this._disposePostProcesses();
  76625. if (this._cameras !== null) {
  76626. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76627. // get back cameras to be used to reattach pipeline
  76628. this._cameras = this._camerasToBeAttached.slice();
  76629. }
  76630. this._reset();
  76631. this._prevPostProcess = null;
  76632. this._prevPrevPostProcess = null;
  76633. this._hasCleared = false;
  76634. if (this.depthOfFieldEnabled) {
  76635. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76636. this.depthOfField.depthTexture = depthTexture;
  76637. if (!this.depthOfField._isReady()) {
  76638. this.depthOfField._updateEffects();
  76639. }
  76640. this.addEffect(this.depthOfField);
  76641. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76642. }
  76643. if (this.bloomEnabled) {
  76644. if (!this.bloom._isReady()) {
  76645. this.bloom._updateEffects();
  76646. }
  76647. this.addEffect(this.bloom);
  76648. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76649. }
  76650. if (this._imageProcessingEnabled) {
  76651. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76652. if (this._hdr) {
  76653. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76654. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76655. }
  76656. else {
  76657. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76658. }
  76659. }
  76660. if (this.sharpenEnabled) {
  76661. if (!this.sharpen.isReady()) {
  76662. this.sharpen.updateEffect();
  76663. }
  76664. this.addEffect(this._sharpenEffect);
  76665. this._setAutoClearAndTextureSharing(this.sharpen);
  76666. }
  76667. if (this.grainEnabled) {
  76668. if (!this.grain.isReady()) {
  76669. this.grain.updateEffect();
  76670. }
  76671. this.addEffect(this._grainEffect);
  76672. this._setAutoClearAndTextureSharing(this.grain);
  76673. }
  76674. if (this.chromaticAberrationEnabled) {
  76675. if (!this.chromaticAberration.isReady()) {
  76676. this.chromaticAberration.updateEffect();
  76677. }
  76678. this.addEffect(this._chromaticAberrationEffect);
  76679. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76680. }
  76681. if (this.fxaaEnabled) {
  76682. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76683. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76684. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76685. }
  76686. if (this._cameras !== null) {
  76687. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76688. }
  76689. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76690. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76691. }
  76692. };
  76693. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76694. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76695. for (var i = 0; i < this._cameras.length; i++) {
  76696. var camera = this._cameras[i];
  76697. if (this.imageProcessing) {
  76698. this.imageProcessing.dispose(camera);
  76699. }
  76700. if (this.fxaa) {
  76701. this.fxaa.dispose(camera);
  76702. }
  76703. // These are created in the constructor and should not be disposed on every pipeline change
  76704. if (disposeNonRecreated) {
  76705. if (this.sharpen) {
  76706. this.sharpen.dispose(camera);
  76707. }
  76708. if (this.depthOfField) {
  76709. this.depthOfField.disposeEffects(camera);
  76710. }
  76711. if (this.bloom) {
  76712. this.bloom.disposeEffects(camera);
  76713. }
  76714. if (this.chromaticAberration) {
  76715. this.chromaticAberration.dispose(camera);
  76716. }
  76717. if (this.grain) {
  76718. this.grain.dispose(camera);
  76719. }
  76720. if (this._glowLayer) {
  76721. this._glowLayer.dispose();
  76722. }
  76723. }
  76724. }
  76725. this.imageProcessing = null;
  76726. this.fxaa = null;
  76727. if (disposeNonRecreated) {
  76728. this.sharpen = null;
  76729. this._sharpenEffect = null;
  76730. this.depthOfField = null;
  76731. this.bloom = null;
  76732. this.chromaticAberration = null;
  76733. this._chromaticAberrationEffect = null;
  76734. this.grain = null;
  76735. this._grainEffect = null;
  76736. this._glowLayer = null;
  76737. }
  76738. };
  76739. /**
  76740. * Adds a camera to the pipeline
  76741. * @param camera the camera to be added
  76742. */
  76743. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76744. this._camerasToBeAttached.push(camera);
  76745. this._buildPipeline();
  76746. };
  76747. /**
  76748. * Removes a camera from the pipeline
  76749. * @param camera the camera to remove
  76750. */
  76751. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76752. var index = this._camerasToBeAttached.indexOf(camera);
  76753. this._camerasToBeAttached.splice(index, 1);
  76754. this._buildPipeline();
  76755. };
  76756. /**
  76757. * Dispose of the pipeline and stop all post processes
  76758. */
  76759. DefaultRenderingPipeline.prototype.dispose = function () {
  76760. this._disposePostProcesses(true);
  76761. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76762. this._scene.autoClear = true;
  76763. if (this._resizeObserver) {
  76764. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76765. this._resizeObserver = null;
  76766. }
  76767. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76768. _super.prototype.dispose.call(this);
  76769. };
  76770. /**
  76771. * Serialize the rendering pipeline (Used when exporting)
  76772. * @returns the serialized object
  76773. */
  76774. DefaultRenderingPipeline.prototype.serialize = function () {
  76775. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76776. serializationObject.customType = "DefaultRenderingPipeline";
  76777. return serializationObject;
  76778. };
  76779. /**
  76780. * Parse the serialized pipeline
  76781. * @param source Source pipeline.
  76782. * @param scene The scene to load the pipeline to.
  76783. * @param rootUrl The URL of the serialized pipeline.
  76784. * @returns An instantiated pipeline from the serialized object.
  76785. */
  76786. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76787. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76788. };
  76789. __decorate([
  76790. BABYLON.serialize()
  76791. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76792. __decorate([
  76793. BABYLON.serialize()
  76794. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76795. __decorate([
  76796. BABYLON.serialize()
  76797. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76798. __decorate([
  76799. BABYLON.serialize()
  76800. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76801. __decorate([
  76802. BABYLON.serialize()
  76803. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76804. __decorate([
  76805. BABYLON.serialize()
  76806. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76807. __decorate([
  76808. BABYLON.serialize()
  76809. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76810. __decorate([
  76811. BABYLON.serialize()
  76812. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76813. __decorate([
  76814. BABYLON.serialize()
  76815. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76816. __decorate([
  76817. BABYLON.serialize()
  76818. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76819. __decorate([
  76820. BABYLON.serialize()
  76821. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76822. __decorate([
  76823. BABYLON.serialize()
  76824. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76825. __decorate([
  76826. BABYLON.serialize()
  76827. ], DefaultRenderingPipeline.prototype, "samples", null);
  76828. __decorate([
  76829. BABYLON.serialize()
  76830. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76831. __decorate([
  76832. BABYLON.serialize()
  76833. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76834. __decorate([
  76835. BABYLON.serialize()
  76836. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76840. return DefaultRenderingPipeline;
  76841. }(BABYLON.PostProcessRenderPipeline));
  76842. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76843. })(BABYLON || (BABYLON = {}));
  76844. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76845. var BABYLON;
  76846. (function (BABYLON) {
  76847. /**
  76848. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76849. */
  76850. var GeometryBufferRenderer = /** @class */ (function () {
  76851. /**
  76852. * Creates a new G Buffer for the scene
  76853. * @param scene The scene the buffer belongs to
  76854. * @param ratio How big is the buffer related to the main canvas.
  76855. */
  76856. function GeometryBufferRenderer(scene, ratio) {
  76857. if (ratio === void 0) { ratio = 1; }
  76858. this._enablePosition = false;
  76859. this._scene = scene;
  76860. this._ratio = ratio;
  76861. // Render target
  76862. this._createRenderTargets();
  76863. }
  76864. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76865. /**
  76866. * Set the render list (meshes to be rendered) used in the G buffer.
  76867. */
  76868. set: function (meshes) {
  76869. this._multiRenderTarget.renderList = meshes;
  76870. },
  76871. enumerable: true,
  76872. configurable: true
  76873. });
  76874. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76875. /**
  76876. * Gets wether or not G buffer are supported by the running hardware.
  76877. * This requires draw buffer supports
  76878. */
  76879. get: function () {
  76880. return this._multiRenderTarget.isSupported;
  76881. },
  76882. enumerable: true,
  76883. configurable: true
  76884. });
  76885. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76886. /**
  76887. * Gets wether or not position are enabled for the G buffer.
  76888. */
  76889. get: function () {
  76890. return this._enablePosition;
  76891. },
  76892. /**
  76893. * Sets wether or not position are enabled for the G buffer.
  76894. */
  76895. set: function (enable) {
  76896. this._enablePosition = enable;
  76897. this.dispose();
  76898. this._createRenderTargets();
  76899. },
  76900. enumerable: true,
  76901. configurable: true
  76902. });
  76903. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76904. /**
  76905. * Gets the scene associated with the buffer.
  76906. */
  76907. get: function () {
  76908. return this._scene;
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76914. /**
  76915. * Gets the ratio used by the buffer during its creation.
  76916. * How big is the buffer related to the main canvas.
  76917. */
  76918. get: function () {
  76919. return this._ratio;
  76920. },
  76921. enumerable: true,
  76922. configurable: true
  76923. });
  76924. /**
  76925. * Checks wether everything is ready to render a submesh to the G buffer.
  76926. * @param subMesh the submesh to check readiness for
  76927. * @param useInstances is the mesh drawn using instance or not
  76928. * @returns true if ready otherwise false
  76929. */
  76930. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76931. var material = subMesh.getMaterial();
  76932. if (material && material.disableDepthWrite) {
  76933. return false;
  76934. }
  76935. var defines = [];
  76936. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76937. var mesh = subMesh.getMesh();
  76938. // Alpha test
  76939. if (material && material.needAlphaTesting()) {
  76940. defines.push("#define ALPHATEST");
  76941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76942. attribs.push(BABYLON.VertexBuffer.UVKind);
  76943. defines.push("#define UV1");
  76944. }
  76945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76946. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76947. defines.push("#define UV2");
  76948. }
  76949. }
  76950. // Buffers
  76951. if (this._enablePosition) {
  76952. defines.push("#define POSITION");
  76953. }
  76954. // Bones
  76955. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76956. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76957. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76958. if (mesh.numBoneInfluencers > 4) {
  76959. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76960. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76961. }
  76962. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76963. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76964. }
  76965. else {
  76966. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76967. }
  76968. // Instances
  76969. if (useInstances) {
  76970. defines.push("#define INSTANCES");
  76971. attribs.push("world0");
  76972. attribs.push("world1");
  76973. attribs.push("world2");
  76974. attribs.push("world3");
  76975. }
  76976. // Get correct effect
  76977. var join = defines.join("\n");
  76978. if (this._cachedDefines !== join) {
  76979. this._cachedDefines = join;
  76980. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76981. }
  76982. return this._effect.isReady();
  76983. };
  76984. /**
  76985. * Gets the current underlying G Buffer.
  76986. * @returns the buffer
  76987. */
  76988. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76989. return this._multiRenderTarget;
  76990. };
  76991. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76992. /**
  76993. * Gets the number of samples used to render the buffer (anti aliasing).
  76994. */
  76995. get: function () {
  76996. return this._multiRenderTarget.samples;
  76997. },
  76998. /**
  76999. * Sets the number of samples used to render the buffer (anti aliasing).
  77000. */
  77001. set: function (value) {
  77002. this._multiRenderTarget.samples = value;
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. /**
  77008. * Disposes the renderer and frees up associated resources.
  77009. */
  77010. GeometryBufferRenderer.prototype.dispose = function () {
  77011. this.getGBuffer().dispose();
  77012. };
  77013. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77014. var _this = this;
  77015. var engine = this._scene.getEngine();
  77016. var count = this._enablePosition ? 3 : 2;
  77017. 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 });
  77018. if (!this.isSupported) {
  77019. return;
  77020. }
  77021. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77022. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77023. this._multiRenderTarget.refreshRate = 1;
  77024. this._multiRenderTarget.renderParticles = false;
  77025. this._multiRenderTarget.renderList = null;
  77026. // set default depth value to 1.0 (far away)
  77027. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77028. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77029. });
  77030. // Custom render function
  77031. var renderSubMesh = function (subMesh) {
  77032. var mesh = subMesh.getRenderingMesh();
  77033. var scene = _this._scene;
  77034. var engine = scene.getEngine();
  77035. var material = subMesh.getMaterial();
  77036. if (!material) {
  77037. return;
  77038. }
  77039. // Culling
  77040. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77041. // Managing instances
  77042. var batch = mesh._getInstancesRenderList(subMesh._id);
  77043. if (batch.mustReturn) {
  77044. return;
  77045. }
  77046. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77047. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77048. engine.enableEffect(_this._effect);
  77049. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77050. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77051. _this._effect.setMatrix("view", scene.getViewMatrix());
  77052. // Alpha test
  77053. if (material && material.needAlphaTesting()) {
  77054. var alphaTexture = material.getAlphaTestTexture();
  77055. if (alphaTexture) {
  77056. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77057. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77058. }
  77059. }
  77060. // Bones
  77061. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77062. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77063. }
  77064. // Draw
  77065. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77066. }
  77067. };
  77068. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77069. var index;
  77070. if (depthOnlySubMeshes.length) {
  77071. engine.setColorWrite(false);
  77072. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77073. renderSubMesh(depthOnlySubMeshes.data[index]);
  77074. }
  77075. engine.setColorWrite(true);
  77076. }
  77077. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77078. renderSubMesh(opaqueSubMeshes.data[index]);
  77079. }
  77080. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77081. renderSubMesh(alphaTestSubMeshes.data[index]);
  77082. }
  77083. };
  77084. };
  77085. return GeometryBufferRenderer;
  77086. }());
  77087. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77088. })(BABYLON || (BABYLON = {}));
  77089. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77090. var BABYLON;
  77091. (function (BABYLON) {
  77092. /**
  77093. * This groups together the common properties used for image processing either in direct forward pass
  77094. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77095. * or not.
  77096. */
  77097. var ImageProcessingConfiguration = /** @class */ (function () {
  77098. function ImageProcessingConfiguration() {
  77099. /**
  77100. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77101. */
  77102. this.colorCurves = new BABYLON.ColorCurves();
  77103. this._colorCurvesEnabled = false;
  77104. this._colorGradingEnabled = false;
  77105. this._colorGradingWithGreenDepth = true;
  77106. this._colorGradingBGR = true;
  77107. this._exposure = 1.0;
  77108. this._toneMappingEnabled = false;
  77109. this._contrast = 1.0;
  77110. /**
  77111. * Vignette stretch size.
  77112. */
  77113. this.vignetteStretch = 0;
  77114. /**
  77115. * Vignette centre X Offset.
  77116. */
  77117. this.vignetteCentreX = 0;
  77118. /**
  77119. * Vignette centre Y Offset.
  77120. */
  77121. this.vignetteCentreY = 0;
  77122. /**
  77123. * Vignette weight or intensity of the vignette effect.
  77124. */
  77125. this.vignetteWeight = 1.5;
  77126. /**
  77127. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77128. * if vignetteEnabled is set to true.
  77129. */
  77130. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77131. /**
  77132. * Camera field of view used by the Vignette effect.
  77133. */
  77134. this.vignetteCameraFov = 0.5;
  77135. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77136. this._vignetteEnabled = false;
  77137. this._applyByPostProcess = false;
  77138. this._isEnabled = true;
  77139. /**
  77140. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77141. */
  77142. this.onUpdateParameters = new BABYLON.Observable();
  77143. }
  77144. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77145. /**
  77146. * Gets wether the color curves effect is enabled.
  77147. */
  77148. get: function () {
  77149. return this._colorCurvesEnabled;
  77150. },
  77151. /**
  77152. * Sets wether the color curves effect is enabled.
  77153. */
  77154. set: function (value) {
  77155. if (this._colorCurvesEnabled === value) {
  77156. return;
  77157. }
  77158. this._colorCurvesEnabled = value;
  77159. this._updateParameters();
  77160. },
  77161. enumerable: true,
  77162. configurable: true
  77163. });
  77164. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77165. /**
  77166. * Gets wether the color grading effect is enabled.
  77167. */
  77168. get: function () {
  77169. return this._colorGradingEnabled;
  77170. },
  77171. /**
  77172. * Sets wether the color grading effect is enabled.
  77173. */
  77174. set: function (value) {
  77175. if (this._colorGradingEnabled === value) {
  77176. return;
  77177. }
  77178. this._colorGradingEnabled = value;
  77179. this._updateParameters();
  77180. },
  77181. enumerable: true,
  77182. configurable: true
  77183. });
  77184. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77185. /**
  77186. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77187. */
  77188. get: function () {
  77189. return this._colorGradingWithGreenDepth;
  77190. },
  77191. /**
  77192. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77193. */
  77194. set: function (value) {
  77195. if (this._colorGradingWithGreenDepth === value) {
  77196. return;
  77197. }
  77198. this._colorGradingWithGreenDepth = value;
  77199. this._updateParameters();
  77200. },
  77201. enumerable: true,
  77202. configurable: true
  77203. });
  77204. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77205. /**
  77206. * Gets wether the color grading texture contains BGR values.
  77207. */
  77208. get: function () {
  77209. return this._colorGradingBGR;
  77210. },
  77211. /**
  77212. * Sets wether the color grading texture contains BGR values.
  77213. */
  77214. set: function (value) {
  77215. if (this._colorGradingBGR === value) {
  77216. return;
  77217. }
  77218. this._colorGradingBGR = value;
  77219. this._updateParameters();
  77220. },
  77221. enumerable: true,
  77222. configurable: true
  77223. });
  77224. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77225. /**
  77226. * Gets the Exposure used in the effect.
  77227. */
  77228. get: function () {
  77229. return this._exposure;
  77230. },
  77231. /**
  77232. * Sets the Exposure used in the effect.
  77233. */
  77234. set: function (value) {
  77235. if (this._exposure === value) {
  77236. return;
  77237. }
  77238. this._exposure = value;
  77239. this._updateParameters();
  77240. },
  77241. enumerable: true,
  77242. configurable: true
  77243. });
  77244. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77245. /**
  77246. * Gets wether the tone mapping effect is enabled.
  77247. */
  77248. get: function () {
  77249. return this._toneMappingEnabled;
  77250. },
  77251. /**
  77252. * Sets wether the tone mapping effect is enabled.
  77253. */
  77254. set: function (value) {
  77255. if (this._toneMappingEnabled === value) {
  77256. return;
  77257. }
  77258. this._toneMappingEnabled = value;
  77259. this._updateParameters();
  77260. },
  77261. enumerable: true,
  77262. configurable: true
  77263. });
  77264. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77265. /**
  77266. * Gets the contrast used in the effect.
  77267. */
  77268. get: function () {
  77269. return this._contrast;
  77270. },
  77271. /**
  77272. * Sets the contrast used in the effect.
  77273. */
  77274. set: function (value) {
  77275. if (this._contrast === value) {
  77276. return;
  77277. }
  77278. this._contrast = value;
  77279. this._updateParameters();
  77280. },
  77281. enumerable: true,
  77282. configurable: true
  77283. });
  77284. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77285. /**
  77286. * Gets the vignette blend mode allowing different kind of effect.
  77287. */
  77288. get: function () {
  77289. return this._vignetteBlendMode;
  77290. },
  77291. /**
  77292. * Sets the vignette blend mode allowing different kind of effect.
  77293. */
  77294. set: function (value) {
  77295. if (this._vignetteBlendMode === value) {
  77296. return;
  77297. }
  77298. this._vignetteBlendMode = value;
  77299. this._updateParameters();
  77300. },
  77301. enumerable: true,
  77302. configurable: true
  77303. });
  77304. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77305. /**
  77306. * Gets wether the vignette effect is enabled.
  77307. */
  77308. get: function () {
  77309. return this._vignetteEnabled;
  77310. },
  77311. /**
  77312. * Sets wether the vignette effect is enabled.
  77313. */
  77314. set: function (value) {
  77315. if (this._vignetteEnabled === value) {
  77316. return;
  77317. }
  77318. this._vignetteEnabled = value;
  77319. this._updateParameters();
  77320. },
  77321. enumerable: true,
  77322. configurable: true
  77323. });
  77324. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77325. /**
  77326. * Gets wether the image processing is applied through a post process or not.
  77327. */
  77328. get: function () {
  77329. return this._applyByPostProcess;
  77330. },
  77331. /**
  77332. * Sets wether the image processing is applied through a post process or not.
  77333. */
  77334. set: function (value) {
  77335. if (this._applyByPostProcess === value) {
  77336. return;
  77337. }
  77338. this._applyByPostProcess = value;
  77339. this._updateParameters();
  77340. },
  77341. enumerable: true,
  77342. configurable: true
  77343. });
  77344. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77345. /**
  77346. * Gets wether the image processing is enabled or not.
  77347. */
  77348. get: function () {
  77349. return this._isEnabled;
  77350. },
  77351. /**
  77352. * Sets wether the image processing is enabled or not.
  77353. */
  77354. set: function (value) {
  77355. if (this._isEnabled === value) {
  77356. return;
  77357. }
  77358. this._isEnabled = value;
  77359. this._updateParameters();
  77360. },
  77361. enumerable: true,
  77362. configurable: true
  77363. });
  77364. /**
  77365. * Method called each time the image processing information changes requires to recompile the effect.
  77366. */
  77367. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77368. this.onUpdateParameters.notifyObservers(this);
  77369. };
  77370. ImageProcessingConfiguration.prototype.getClassName = function () {
  77371. return "ImageProcessingConfiguration";
  77372. };
  77373. /**
  77374. * Prepare the list of uniforms associated with the Image Processing effects.
  77375. * @param uniformsList The list of uniforms used in the effect
  77376. * @param defines the list of defines currently in use
  77377. */
  77378. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77379. if (defines.EXPOSURE) {
  77380. uniforms.push("exposureLinear");
  77381. }
  77382. if (defines.CONTRAST) {
  77383. uniforms.push("contrast");
  77384. }
  77385. if (defines.COLORGRADING) {
  77386. uniforms.push("colorTransformSettings");
  77387. }
  77388. if (defines.VIGNETTE) {
  77389. uniforms.push("vInverseScreenSize");
  77390. uniforms.push("vignetteSettings1");
  77391. uniforms.push("vignetteSettings2");
  77392. }
  77393. if (defines.COLORCURVES) {
  77394. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77395. }
  77396. };
  77397. /**
  77398. * Prepare the list of samplers associated with the Image Processing effects.
  77399. * @param uniformsList The list of uniforms used in the effect
  77400. * @param defines the list of defines currently in use
  77401. */
  77402. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77403. if (defines.COLORGRADING) {
  77404. samplersList.push("txColorTransform");
  77405. }
  77406. };
  77407. /**
  77408. * Prepare the list of defines associated to the shader.
  77409. * @param defines the list of defines to complete
  77410. */
  77411. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77412. if (forPostProcess === void 0) { forPostProcess = false; }
  77413. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77414. defines.VIGNETTE = false;
  77415. defines.TONEMAPPING = false;
  77416. defines.CONTRAST = false;
  77417. defines.EXPOSURE = false;
  77418. defines.COLORCURVES = false;
  77419. defines.COLORGRADING = false;
  77420. defines.COLORGRADING3D = false;
  77421. defines.IMAGEPROCESSING = false;
  77422. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77423. return;
  77424. }
  77425. defines.VIGNETTE = this.vignetteEnabled;
  77426. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77427. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77428. defines.TONEMAPPING = this.toneMappingEnabled;
  77429. defines.CONTRAST = (this.contrast !== 1.0);
  77430. defines.EXPOSURE = (this.exposure !== 1.0);
  77431. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77432. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77433. if (defines.COLORGRADING) {
  77434. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77435. }
  77436. else {
  77437. defines.COLORGRADING3D = false;
  77438. }
  77439. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77440. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77441. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77442. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77443. };
  77444. /**
  77445. * Returns true if all the image processing information are ready.
  77446. */
  77447. ImageProcessingConfiguration.prototype.isReady = function () {
  77448. // Color Grading texure can not be none blocking.
  77449. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77450. };
  77451. /**
  77452. * Binds the image processing to the shader.
  77453. * @param effect The effect to bind to
  77454. */
  77455. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77456. if (aspectRatio === void 0) { aspectRatio = 1; }
  77457. // Color Curves
  77458. if (this._colorCurvesEnabled && this.colorCurves) {
  77459. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77460. }
  77461. // Vignette
  77462. if (this._vignetteEnabled) {
  77463. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77464. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77465. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77466. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77467. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77468. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77469. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77470. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77471. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77472. var vignettePower = -2.0 * this.vignetteWeight;
  77473. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77474. }
  77475. // Exposure
  77476. effect.setFloat("exposureLinear", this.exposure);
  77477. // Contrast
  77478. effect.setFloat("contrast", this.contrast);
  77479. // Color transform settings
  77480. if (this.colorGradingTexture) {
  77481. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77482. var textureSize = this.colorGradingTexture.getSize().height;
  77483. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77484. 0.5 / textureSize, // textureOffset
  77485. textureSize, // textureSize
  77486. this.colorGradingTexture.level // weight
  77487. );
  77488. }
  77489. };
  77490. /**
  77491. * Clones the current image processing instance.
  77492. * @return The cloned image processing
  77493. */
  77494. ImageProcessingConfiguration.prototype.clone = function () {
  77495. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77496. };
  77497. /**
  77498. * Serializes the current image processing instance to a json representation.
  77499. * @return a JSON representation
  77500. */
  77501. ImageProcessingConfiguration.prototype.serialize = function () {
  77502. return BABYLON.SerializationHelper.Serialize(this);
  77503. };
  77504. /**
  77505. * Parses the image processing from a json representation.
  77506. * @param source the JSON source to parse
  77507. * @return The parsed image processing
  77508. */
  77509. ImageProcessingConfiguration.Parse = function (source) {
  77510. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77511. };
  77512. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77513. /**
  77514. * Used to apply the vignette as a mix with the pixel color.
  77515. */
  77516. get: function () {
  77517. return this._VIGNETTEMODE_MULTIPLY;
  77518. },
  77519. enumerable: true,
  77520. configurable: true
  77521. });
  77522. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77523. /**
  77524. * Used to apply the vignette as a replacement of the pixel color.
  77525. */
  77526. get: function () {
  77527. return this._VIGNETTEMODE_OPAQUE;
  77528. },
  77529. enumerable: true,
  77530. configurable: true
  77531. });
  77532. // Static constants associated to the image processing.
  77533. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77534. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77535. __decorate([
  77536. BABYLON.serializeAsColorCurves()
  77537. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77538. __decorate([
  77539. BABYLON.serialize()
  77540. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77541. __decorate([
  77542. BABYLON.serializeAsTexture()
  77543. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77544. __decorate([
  77545. BABYLON.serialize()
  77546. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77547. __decorate([
  77548. BABYLON.serialize()
  77549. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77550. __decorate([
  77551. BABYLON.serialize()
  77552. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77553. __decorate([
  77554. BABYLON.serialize()
  77555. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77556. __decorate([
  77557. BABYLON.serialize()
  77558. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77559. __decorate([
  77560. BABYLON.serialize()
  77561. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77562. __decorate([
  77563. BABYLON.serialize()
  77564. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77565. __decorate([
  77566. BABYLON.serialize()
  77567. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77568. __decorate([
  77569. BABYLON.serialize()
  77570. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77571. __decorate([
  77572. BABYLON.serialize()
  77573. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77574. __decorate([
  77575. BABYLON.serializeAsColor4()
  77576. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77577. __decorate([
  77578. BABYLON.serialize()
  77579. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77580. __decorate([
  77581. BABYLON.serialize()
  77582. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77583. __decorate([
  77584. BABYLON.serialize()
  77585. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77586. __decorate([
  77587. BABYLON.serialize()
  77588. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77589. __decorate([
  77590. BABYLON.serialize()
  77591. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77592. return ImageProcessingConfiguration;
  77593. }());
  77594. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77595. })(BABYLON || (BABYLON = {}));
  77596. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77597. var BABYLON;
  77598. (function (BABYLON) {
  77599. /**
  77600. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77601. * It can help converting any input color in a desired output one. This can then be used to create effects
  77602. * from sepia, black and white to sixties or futuristic rendering...
  77603. *
  77604. * The only supported format is currently 3dl.
  77605. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77606. */
  77607. var ColorGradingTexture = /** @class */ (function (_super) {
  77608. __extends(ColorGradingTexture, _super);
  77609. /**
  77610. * Instantiates a ColorGradingTexture from the following parameters.
  77611. *
  77612. * @param url The location of the color gradind data (currently only supporting 3dl)
  77613. * @param scene The scene the texture will be used in
  77614. */
  77615. function ColorGradingTexture(url, scene) {
  77616. var _this = _super.call(this, scene) || this;
  77617. if (!url) {
  77618. return _this;
  77619. }
  77620. _this._engine = scene.getEngine();
  77621. _this._textureMatrix = BABYLON.Matrix.Identity();
  77622. _this.name = url;
  77623. _this.url = url;
  77624. _this.hasAlpha = false;
  77625. _this.isCube = false;
  77626. _this.is3D = _this._engine.webGLVersion > 1;
  77627. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77628. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77629. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77630. _this.anisotropicFilteringLevel = 1;
  77631. _this._texture = _this._getFromCache(url, true);
  77632. if (!_this._texture) {
  77633. if (!scene.useDelayedTextureLoading) {
  77634. _this.loadTexture();
  77635. }
  77636. else {
  77637. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77638. }
  77639. }
  77640. return _this;
  77641. }
  77642. /**
  77643. * Returns the texture matrix used in most of the material.
  77644. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77645. */
  77646. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77647. return this._textureMatrix;
  77648. };
  77649. /**
  77650. * Occurs when the file being loaded is a .3dl LUT file.
  77651. */
  77652. ColorGradingTexture.prototype.load3dlTexture = function () {
  77653. var engine = this._engine;
  77654. var texture;
  77655. if (engine.webGLVersion === 1) {
  77656. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77657. }
  77658. else {
  77659. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77660. }
  77661. this._texture = texture;
  77662. var callback = function (text) {
  77663. if (typeof text !== "string") {
  77664. return;
  77665. }
  77666. var data = null;
  77667. var tempData = null;
  77668. var line;
  77669. var lines = text.split('\n');
  77670. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77671. var maxColor = 0;
  77672. for (var i = 0; i < lines.length; i++) {
  77673. line = lines[i];
  77674. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77675. continue;
  77676. if (line.indexOf('#') === 0)
  77677. continue;
  77678. var words = line.split(" ");
  77679. if (size === 0) {
  77680. // Number of space + one
  77681. size = words.length;
  77682. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77683. tempData = new Float32Array(size * size * size * 4);
  77684. continue;
  77685. }
  77686. if (size != 0) {
  77687. var r = Math.max(parseInt(words[0]), 0);
  77688. var g = Math.max(parseInt(words[1]), 0);
  77689. var b = Math.max(parseInt(words[2]), 0);
  77690. maxColor = Math.max(r, maxColor);
  77691. maxColor = Math.max(g, maxColor);
  77692. maxColor = Math.max(b, maxColor);
  77693. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77694. if (tempData) {
  77695. tempData[pixelStorageIndex + 0] = r;
  77696. tempData[pixelStorageIndex + 1] = g;
  77697. tempData[pixelStorageIndex + 2] = b;
  77698. }
  77699. pixelIndexSlice++;
  77700. if (pixelIndexSlice % size == 0) {
  77701. pixelIndexH++;
  77702. pixelIndexSlice = 0;
  77703. if (pixelIndexH % size == 0) {
  77704. pixelIndexW++;
  77705. pixelIndexH = 0;
  77706. }
  77707. }
  77708. }
  77709. }
  77710. if (tempData && data) {
  77711. for (var i = 0; i < tempData.length; i++) {
  77712. if (i > 0 && (i + 1) % 4 === 0) {
  77713. data[i] = 255;
  77714. }
  77715. else {
  77716. var value = tempData[i];
  77717. data[i] = (value / maxColor * 255);
  77718. }
  77719. }
  77720. }
  77721. if (texture.is3D) {
  77722. texture.updateSize(size, size, size);
  77723. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77724. }
  77725. else {
  77726. texture.updateSize(size * size, size);
  77727. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77728. }
  77729. };
  77730. var scene = this.getScene();
  77731. if (scene) {
  77732. scene._loadFile(this.url, callback);
  77733. }
  77734. else {
  77735. this._engine._loadFile(this.url, callback);
  77736. }
  77737. return this._texture;
  77738. };
  77739. /**
  77740. * Starts the loading process of the texture.
  77741. */
  77742. ColorGradingTexture.prototype.loadTexture = function () {
  77743. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77744. this.load3dlTexture();
  77745. }
  77746. };
  77747. /**
  77748. * Clones the color gradind texture.
  77749. */
  77750. ColorGradingTexture.prototype.clone = function () {
  77751. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77752. // Base texture
  77753. newTexture.level = this.level;
  77754. return newTexture;
  77755. };
  77756. /**
  77757. * Called during delayed load for textures.
  77758. */
  77759. ColorGradingTexture.prototype.delayLoad = function () {
  77760. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77761. return;
  77762. }
  77763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77764. this._texture = this._getFromCache(this.url, true);
  77765. if (!this._texture) {
  77766. this.loadTexture();
  77767. }
  77768. };
  77769. /**
  77770. * Parses a color grading texture serialized by Babylon.
  77771. * @param parsedTexture The texture information being parsedTexture
  77772. * @param scene The scene to load the texture in
  77773. * @param rootUrl The root url of the data assets to load
  77774. * @return A color gradind texture
  77775. */
  77776. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77777. var texture = null;
  77778. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77779. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77780. texture.name = parsedTexture.name;
  77781. texture.level = parsedTexture.level;
  77782. }
  77783. return texture;
  77784. };
  77785. /**
  77786. * Serializes the LUT texture to json format.
  77787. */
  77788. ColorGradingTexture.prototype.serialize = function () {
  77789. if (!this.name) {
  77790. return null;
  77791. }
  77792. var serializationObject = {};
  77793. serializationObject.name = this.name;
  77794. serializationObject.level = this.level;
  77795. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77796. return serializationObject;
  77797. };
  77798. /**
  77799. * Empty line regex stored for GC.
  77800. */
  77801. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77802. return ColorGradingTexture;
  77803. }(BABYLON.BaseTexture));
  77804. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77805. })(BABYLON || (BABYLON = {}));
  77806. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77807. var BABYLON;
  77808. (function (BABYLON) {
  77809. /**
  77810. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77811. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77812. * 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;
  77813. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77814. */
  77815. var ColorCurves = /** @class */ (function () {
  77816. function ColorCurves() {
  77817. this._dirty = true;
  77818. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77819. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77820. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77821. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77822. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77823. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77824. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77825. this._globalHue = 30;
  77826. this._globalDensity = 0;
  77827. this._globalSaturation = 0;
  77828. this._globalExposure = 0;
  77829. this._highlightsHue = 30;
  77830. this._highlightsDensity = 0;
  77831. this._highlightsSaturation = 0;
  77832. this._highlightsExposure = 0;
  77833. this._midtonesHue = 30;
  77834. this._midtonesDensity = 0;
  77835. this._midtonesSaturation = 0;
  77836. this._midtonesExposure = 0;
  77837. this._shadowsHue = 30;
  77838. this._shadowsDensity = 0;
  77839. this._shadowsSaturation = 0;
  77840. this._shadowsExposure = 0;
  77841. }
  77842. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77843. /**
  77844. * Gets the global Hue value.
  77845. * 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).
  77846. */
  77847. get: function () {
  77848. return this._globalHue;
  77849. },
  77850. /**
  77851. * Sets the global Hue value.
  77852. * 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).
  77853. */
  77854. set: function (value) {
  77855. this._globalHue = value;
  77856. this._dirty = true;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77862. /**
  77863. * Gets the global Density value.
  77864. * 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.
  77865. * Values less than zero provide a filter of opposite hue.
  77866. */
  77867. get: function () {
  77868. return this._globalDensity;
  77869. },
  77870. /**
  77871. * Sets the global Density value.
  77872. * 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.
  77873. * Values less than zero provide a filter of opposite hue.
  77874. */
  77875. set: function (value) {
  77876. this._globalDensity = value;
  77877. this._dirty = true;
  77878. },
  77879. enumerable: true,
  77880. configurable: true
  77881. });
  77882. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77883. /**
  77884. * Gets the global Saturation value.
  77885. * 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.
  77886. */
  77887. get: function () {
  77888. return this._globalSaturation;
  77889. },
  77890. /**
  77891. * Sets the global Saturation value.
  77892. * 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.
  77893. */
  77894. set: function (value) {
  77895. this._globalSaturation = value;
  77896. this._dirty = true;
  77897. },
  77898. enumerable: true,
  77899. configurable: true
  77900. });
  77901. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77902. /**
  77903. * Gets the global Exposure value.
  77904. * 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.
  77905. */
  77906. get: function () {
  77907. return this._globalExposure;
  77908. },
  77909. /**
  77910. * Sets the global Exposure value.
  77911. * 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.
  77912. */
  77913. set: function (value) {
  77914. this._globalExposure = value;
  77915. this._dirty = true;
  77916. },
  77917. enumerable: true,
  77918. configurable: true
  77919. });
  77920. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77921. /**
  77922. * Gets the highlights Hue value.
  77923. * 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).
  77924. */
  77925. get: function () {
  77926. return this._highlightsHue;
  77927. },
  77928. /**
  77929. * Sets the highlights Hue value.
  77930. * 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).
  77931. */
  77932. set: function (value) {
  77933. this._highlightsHue = value;
  77934. this._dirty = true;
  77935. },
  77936. enumerable: true,
  77937. configurable: true
  77938. });
  77939. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77940. /**
  77941. * Gets the highlights Density value.
  77942. * 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.
  77943. * Values less than zero provide a filter of opposite hue.
  77944. */
  77945. get: function () {
  77946. return this._highlightsDensity;
  77947. },
  77948. /**
  77949. * Sets the highlights Density value.
  77950. * 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.
  77951. * Values less than zero provide a filter of opposite hue.
  77952. */
  77953. set: function (value) {
  77954. this._highlightsDensity = value;
  77955. this._dirty = true;
  77956. },
  77957. enumerable: true,
  77958. configurable: true
  77959. });
  77960. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77961. /**
  77962. * Gets the highlights Saturation value.
  77963. * 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.
  77964. */
  77965. get: function () {
  77966. return this._highlightsSaturation;
  77967. },
  77968. /**
  77969. * Sets the highlights Saturation value.
  77970. * 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.
  77971. */
  77972. set: function (value) {
  77973. this._highlightsSaturation = value;
  77974. this._dirty = true;
  77975. },
  77976. enumerable: true,
  77977. configurable: true
  77978. });
  77979. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77980. /**
  77981. * Gets the highlights Exposure value.
  77982. * 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.
  77983. */
  77984. get: function () {
  77985. return this._highlightsExposure;
  77986. },
  77987. /**
  77988. * Sets the highlights Exposure value.
  77989. * 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.
  77990. */
  77991. set: function (value) {
  77992. this._highlightsExposure = value;
  77993. this._dirty = true;
  77994. },
  77995. enumerable: true,
  77996. configurable: true
  77997. });
  77998. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77999. /**
  78000. * Gets the midtones Hue value.
  78001. * 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).
  78002. */
  78003. get: function () {
  78004. return this._midtonesHue;
  78005. },
  78006. /**
  78007. * Sets the midtones Hue value.
  78008. * 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).
  78009. */
  78010. set: function (value) {
  78011. this._midtonesHue = value;
  78012. this._dirty = true;
  78013. },
  78014. enumerable: true,
  78015. configurable: true
  78016. });
  78017. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78018. /**
  78019. * Gets the midtones Density value.
  78020. * 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.
  78021. * Values less than zero provide a filter of opposite hue.
  78022. */
  78023. get: function () {
  78024. return this._midtonesDensity;
  78025. },
  78026. /**
  78027. * Sets the midtones Density value.
  78028. * 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.
  78029. * Values less than zero provide a filter of opposite hue.
  78030. */
  78031. set: function (value) {
  78032. this._midtonesDensity = value;
  78033. this._dirty = true;
  78034. },
  78035. enumerable: true,
  78036. configurable: true
  78037. });
  78038. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78039. /**
  78040. * Gets the midtones Saturation value.
  78041. * 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.
  78042. */
  78043. get: function () {
  78044. return this._midtonesSaturation;
  78045. },
  78046. /**
  78047. * Sets the midtones Saturation value.
  78048. * 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.
  78049. */
  78050. set: function (value) {
  78051. this._midtonesSaturation = value;
  78052. this._dirty = true;
  78053. },
  78054. enumerable: true,
  78055. configurable: true
  78056. });
  78057. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78058. /**
  78059. * Gets the midtones Exposure value.
  78060. * 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.
  78061. */
  78062. get: function () {
  78063. return this._midtonesExposure;
  78064. },
  78065. /**
  78066. * Sets the midtones Exposure value.
  78067. * 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.
  78068. */
  78069. set: function (value) {
  78070. this._midtonesExposure = value;
  78071. this._dirty = true;
  78072. },
  78073. enumerable: true,
  78074. configurable: true
  78075. });
  78076. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78077. /**
  78078. * Gets the shadows Hue value.
  78079. * 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).
  78080. */
  78081. get: function () {
  78082. return this._shadowsHue;
  78083. },
  78084. /**
  78085. * Sets the shadows Hue value.
  78086. * 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).
  78087. */
  78088. set: function (value) {
  78089. this._shadowsHue = value;
  78090. this._dirty = true;
  78091. },
  78092. enumerable: true,
  78093. configurable: true
  78094. });
  78095. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78096. /**
  78097. * Gets the shadows Density value.
  78098. * 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.
  78099. * Values less than zero provide a filter of opposite hue.
  78100. */
  78101. get: function () {
  78102. return this._shadowsDensity;
  78103. },
  78104. /**
  78105. * Sets the shadows Density value.
  78106. * 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.
  78107. * Values less than zero provide a filter of opposite hue.
  78108. */
  78109. set: function (value) {
  78110. this._shadowsDensity = value;
  78111. this._dirty = true;
  78112. },
  78113. enumerable: true,
  78114. configurable: true
  78115. });
  78116. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78117. /**
  78118. * Gets the shadows Saturation value.
  78119. * 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.
  78120. */
  78121. get: function () {
  78122. return this._shadowsSaturation;
  78123. },
  78124. /**
  78125. * Sets the shadows Saturation value.
  78126. * 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.
  78127. */
  78128. set: function (value) {
  78129. this._shadowsSaturation = value;
  78130. this._dirty = true;
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78136. /**
  78137. * Gets the shadows Exposure value.
  78138. * 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.
  78139. */
  78140. get: function () {
  78141. return this._shadowsExposure;
  78142. },
  78143. /**
  78144. * Sets the shadows Exposure value.
  78145. * 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.
  78146. */
  78147. set: function (value) {
  78148. this._shadowsExposure = value;
  78149. this._dirty = true;
  78150. },
  78151. enumerable: true,
  78152. configurable: true
  78153. });
  78154. ColorCurves.prototype.getClassName = function () {
  78155. return "ColorCurves";
  78156. };
  78157. /**
  78158. * Binds the color curves to the shader.
  78159. * @param colorCurves The color curve to bind
  78160. * @param effect The effect to bind to
  78161. */
  78162. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78163. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78164. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78165. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78166. if (colorCurves._dirty) {
  78167. colorCurves._dirty = false;
  78168. // Fill in global info.
  78169. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78170. // Compute highlights info.
  78171. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78172. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78173. // Compute midtones info.
  78174. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78175. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78176. // Compute shadows info.
  78177. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78178. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78179. // Compute deltas (neutral is midtones).
  78180. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78181. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78182. }
  78183. if (effect) {
  78184. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78185. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78186. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78187. }
  78188. };
  78189. /**
  78190. * Prepare the list of uniforms associated with the ColorCurves effects.
  78191. * @param uniformsList The list of uniforms used in the effect
  78192. */
  78193. ColorCurves.PrepareUniforms = function (uniformsList) {
  78194. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78195. };
  78196. /**
  78197. * Returns color grading data based on a hue, density, saturation and exposure value.
  78198. * @param filterHue The hue of the color filter.
  78199. * @param filterDensity The density of the color filter.
  78200. * @param saturation The saturation.
  78201. * @param exposure The exposure.
  78202. * @param result The result data container.
  78203. */
  78204. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78205. if (hue == null) {
  78206. return;
  78207. }
  78208. hue = ColorCurves.clamp(hue, 0, 360);
  78209. density = ColorCurves.clamp(density, -100, 100);
  78210. saturation = ColorCurves.clamp(saturation, -100, 100);
  78211. exposure = ColorCurves.clamp(exposure, -100, 100);
  78212. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78213. // so that the maximum filter density is only 50% control. This provides fine control
  78214. // for small values and reasonable range.
  78215. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78216. density *= 0.5;
  78217. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78218. if (density < 0) {
  78219. density *= -1;
  78220. hue = (hue + 180) % 360;
  78221. }
  78222. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78223. result.scaleToRef(2, result);
  78224. result.a = 1 + 0.01 * saturation;
  78225. };
  78226. /**
  78227. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78228. * @param value The input slider value in range [-100,100].
  78229. * @returns Adjusted value.
  78230. */
  78231. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78232. value /= 100;
  78233. var x = Math.abs(value);
  78234. x = Math.pow(x, 2);
  78235. if (value < 0) {
  78236. x *= -1;
  78237. }
  78238. x *= 100;
  78239. return x;
  78240. };
  78241. /**
  78242. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78243. * @param hue The hue (H) input.
  78244. * @param saturation The saturation (S) input.
  78245. * @param brightness The brightness (B) input.
  78246. * @result An RGBA color represented as Vector4.
  78247. */
  78248. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78249. var h = ColorCurves.clamp(hue, 0, 360);
  78250. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78251. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78252. if (s === 0) {
  78253. result.r = v;
  78254. result.g = v;
  78255. result.b = v;
  78256. }
  78257. else {
  78258. // sector 0 to 5
  78259. h /= 60;
  78260. var i = Math.floor(h);
  78261. // fractional part of h
  78262. var f = h - i;
  78263. var p = v * (1 - s);
  78264. var q = v * (1 - s * f);
  78265. var t = v * (1 - s * (1 - f));
  78266. switch (i) {
  78267. case 0:
  78268. result.r = v;
  78269. result.g = t;
  78270. result.b = p;
  78271. break;
  78272. case 1:
  78273. result.r = q;
  78274. result.g = v;
  78275. result.b = p;
  78276. break;
  78277. case 2:
  78278. result.r = p;
  78279. result.g = v;
  78280. result.b = t;
  78281. break;
  78282. case 3:
  78283. result.r = p;
  78284. result.g = q;
  78285. result.b = v;
  78286. break;
  78287. case 4:
  78288. result.r = t;
  78289. result.g = p;
  78290. result.b = v;
  78291. break;
  78292. default: // case 5:
  78293. result.r = v;
  78294. result.g = p;
  78295. result.b = q;
  78296. break;
  78297. }
  78298. }
  78299. result.a = 1;
  78300. };
  78301. /**
  78302. * Returns a value clamped between min and max
  78303. * @param value The value to clamp
  78304. * @param min The minimum of value
  78305. * @param max The maximum of value
  78306. * @returns The clamped value.
  78307. */
  78308. ColorCurves.clamp = function (value, min, max) {
  78309. return Math.min(Math.max(value, min), max);
  78310. };
  78311. /**
  78312. * Clones the current color curve instance.
  78313. * @return The cloned curves
  78314. */
  78315. ColorCurves.prototype.clone = function () {
  78316. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78317. };
  78318. /**
  78319. * Serializes the current color curve instance to a json representation.
  78320. * @return a JSON representation
  78321. */
  78322. ColorCurves.prototype.serialize = function () {
  78323. return BABYLON.SerializationHelper.Serialize(this);
  78324. };
  78325. /**
  78326. * Parses the color curve from a json representation.
  78327. * @param source the JSON source to parse
  78328. * @return The parsed curves
  78329. */
  78330. ColorCurves.Parse = function (source) {
  78331. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78332. };
  78333. __decorate([
  78334. BABYLON.serialize()
  78335. ], ColorCurves.prototype, "_globalHue", void 0);
  78336. __decorate([
  78337. BABYLON.serialize()
  78338. ], ColorCurves.prototype, "_globalDensity", void 0);
  78339. __decorate([
  78340. BABYLON.serialize()
  78341. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78342. __decorate([
  78343. BABYLON.serialize()
  78344. ], ColorCurves.prototype, "_globalExposure", void 0);
  78345. __decorate([
  78346. BABYLON.serialize()
  78347. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78348. __decorate([
  78349. BABYLON.serialize()
  78350. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78351. __decorate([
  78352. BABYLON.serialize()
  78353. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78354. __decorate([
  78355. BABYLON.serialize()
  78356. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78357. __decorate([
  78358. BABYLON.serialize()
  78359. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78360. __decorate([
  78361. BABYLON.serialize()
  78362. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78363. __decorate([
  78364. BABYLON.serialize()
  78365. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78366. __decorate([
  78367. BABYLON.serialize()
  78368. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78369. return ColorCurves;
  78370. }());
  78371. BABYLON.ColorCurves = ColorCurves;
  78372. })(BABYLON || (BABYLON = {}));
  78373. //# sourceMappingURL=babylon.colorCurves.js.map
  78374. var BABYLON;
  78375. (function (BABYLON) {
  78376. var RefractionPostProcess = /** @class */ (function (_super) {
  78377. __extends(RefractionPostProcess, _super);
  78378. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78379. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78380. _this.color = color;
  78381. _this.depth = depth;
  78382. _this.colorLevel = colorLevel;
  78383. _this._ownRefractionTexture = true;
  78384. _this.onActivateObservable.add(function (cam) {
  78385. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78386. });
  78387. _this.onApplyObservable.add(function (effect) {
  78388. effect.setColor3("baseColor", _this.color);
  78389. effect.setFloat("depth", _this.depth);
  78390. effect.setFloat("colorLevel", _this.colorLevel);
  78391. effect.setTexture("refractionSampler", _this._refTexture);
  78392. });
  78393. return _this;
  78394. }
  78395. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78396. /**
  78397. * Gets or sets the refraction texture
  78398. * Please note that you are responsible for disposing the texture if you set it manually
  78399. */
  78400. get: function () {
  78401. return this._refTexture;
  78402. },
  78403. set: function (value) {
  78404. if (this._refTexture && this._ownRefractionTexture) {
  78405. this._refTexture.dispose();
  78406. }
  78407. this._refTexture = value;
  78408. this._ownRefractionTexture = false;
  78409. },
  78410. enumerable: true,
  78411. configurable: true
  78412. });
  78413. // Methods
  78414. RefractionPostProcess.prototype.dispose = function (camera) {
  78415. if (this._refTexture && this._ownRefractionTexture) {
  78416. this._refTexture.dispose();
  78417. this._refTexture = null;
  78418. }
  78419. _super.prototype.dispose.call(this, camera);
  78420. };
  78421. return RefractionPostProcess;
  78422. }(BABYLON.PostProcess));
  78423. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78424. })(BABYLON || (BABYLON = {}));
  78425. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78426. var BABYLON;
  78427. (function (BABYLON) {
  78428. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78429. __extends(BlackAndWhitePostProcess, _super);
  78430. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78431. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78432. _this.degree = 1;
  78433. _this.onApplyObservable.add(function (effect) {
  78434. effect.setFloat("degree", _this.degree);
  78435. });
  78436. return _this;
  78437. }
  78438. return BlackAndWhitePostProcess;
  78439. }(BABYLON.PostProcess));
  78440. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78441. })(BABYLON || (BABYLON = {}));
  78442. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78443. var BABYLON;
  78444. (function (BABYLON) {
  78445. /**
  78446. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78447. * input texture to perform effects such as edge detection or sharpening
  78448. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78449. */
  78450. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78451. __extends(ConvolutionPostProcess, _super);
  78452. /**
  78453. * Creates a new instance ConvolutionPostProcess
  78454. * @param name The name of the effect.
  78455. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78456. * @param options The required width/height ratio to downsize to before computing the render pass.
  78457. * @param camera The camera to apply the render pass to.
  78458. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78459. * @param engine The engine which the post process will be applied. (default: current engine)
  78460. * @param reusable If the post process can be reused on the same frame. (default: false)
  78461. * @param textureType Type of textures used when performing the post process. (default: 0)
  78462. */
  78463. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78464. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78465. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78466. _this.kernel = kernel;
  78467. _this.onApply = function (effect) {
  78468. effect.setFloat2("screenSize", _this.width, _this.height);
  78469. effect.setArray("kernel", _this.kernel);
  78470. };
  78471. return _this;
  78472. }
  78473. // Statics
  78474. /**
  78475. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78476. */
  78477. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78478. /**
  78479. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78480. */
  78481. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78482. /**
  78483. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78484. */
  78485. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78486. /**
  78487. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78488. */
  78489. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78490. /**
  78491. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78492. */
  78493. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78494. /**
  78495. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78496. */
  78497. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78498. return ConvolutionPostProcess;
  78499. }(BABYLON.PostProcess));
  78500. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78501. })(BABYLON || (BABYLON = {}));
  78502. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78503. var BABYLON;
  78504. (function (BABYLON) {
  78505. var FilterPostProcess = /** @class */ (function (_super) {
  78506. __extends(FilterPostProcess, _super);
  78507. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78508. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78509. _this.kernelMatrix = kernelMatrix;
  78510. _this.onApply = function (effect) {
  78511. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78512. };
  78513. return _this;
  78514. }
  78515. return FilterPostProcess;
  78516. }(BABYLON.PostProcess));
  78517. BABYLON.FilterPostProcess = FilterPostProcess;
  78518. })(BABYLON || (BABYLON = {}));
  78519. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78520. var BABYLON;
  78521. (function (BABYLON) {
  78522. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78523. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78524. __extends(VolumetricLightScatteringPostProcess, _super);
  78525. /**
  78526. * @constructor
  78527. * @param {string} name - The post-process name
  78528. * @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)
  78529. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78530. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78531. * @param {number} samples - The post-process quality, default 100
  78532. * @param {number} samplingMode - The post-process filtering mode
  78533. * @param {BABYLON.Engine} engine - The babylon engine
  78534. * @param {boolean} reusable - If the post-process is reusable
  78535. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78536. */
  78537. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78538. if (samples === void 0) { samples = 100; }
  78539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78540. 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;
  78541. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78542. /**
  78543. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78544. */
  78545. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78546. /**
  78547. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78548. */
  78549. _this.useCustomMeshPosition = false;
  78550. /**
  78551. * If the post-process should inverse the light scattering direction
  78552. */
  78553. _this.invert = true;
  78554. /**
  78555. * Array containing the excluded meshes not rendered in the internal pass
  78556. */
  78557. _this.excludedMeshes = new Array();
  78558. /**
  78559. * Controls the overall intensity of the post-process
  78560. */
  78561. _this.exposure = 0.3;
  78562. /**
  78563. * Dissipates each sample's contribution in range [0, 1]
  78564. */
  78565. _this.decay = 0.96815;
  78566. /**
  78567. * Controls the overall intensity of each sample
  78568. */
  78569. _this.weight = 0.58767;
  78570. /**
  78571. * Controls the density of each sample
  78572. */
  78573. _this.density = 0.926;
  78574. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78575. engine = scene.getEngine();
  78576. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78577. // Configure mesh
  78578. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78579. // Configure
  78580. _this._createPass(scene, ratio.passRatio || ratio);
  78581. _this.onActivate = function (camera) {
  78582. if (!_this.isSupported) {
  78583. _this.dispose(camera);
  78584. }
  78585. _this.onActivate = null;
  78586. };
  78587. _this.onApplyObservable.add(function (effect) {
  78588. _this._updateMeshScreenCoordinates(scene);
  78589. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78590. effect.setFloat("exposure", _this.exposure);
  78591. effect.setFloat("decay", _this.decay);
  78592. effect.setFloat("weight", _this.weight);
  78593. effect.setFloat("density", _this.density);
  78594. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78595. });
  78596. return _this;
  78597. }
  78598. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78599. get: function () {
  78600. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78601. return false;
  78602. },
  78603. set: function (useDiffuseColor) {
  78604. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78605. },
  78606. enumerable: true,
  78607. configurable: true
  78608. });
  78609. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78610. return "VolumetricLightScatteringPostProcess";
  78611. };
  78612. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78613. var mesh = subMesh.getMesh();
  78614. // Render this.mesh as default
  78615. if (mesh === this.mesh && mesh.material) {
  78616. return mesh.material.isReady(mesh);
  78617. }
  78618. var defines = [];
  78619. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78620. var material = subMesh.getMaterial();
  78621. // Alpha test
  78622. if (material) {
  78623. if (material.needAlphaTesting()) {
  78624. defines.push("#define ALPHATEST");
  78625. }
  78626. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78627. attribs.push(BABYLON.VertexBuffer.UVKind);
  78628. defines.push("#define UV1");
  78629. }
  78630. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78631. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78632. defines.push("#define UV2");
  78633. }
  78634. }
  78635. // Bones
  78636. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78640. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78641. }
  78642. else {
  78643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78644. }
  78645. // Instances
  78646. if (useInstances) {
  78647. defines.push("#define INSTANCES");
  78648. attribs.push("world0");
  78649. attribs.push("world1");
  78650. attribs.push("world2");
  78651. attribs.push("world3");
  78652. }
  78653. // Get correct effect
  78654. var join = defines.join("\n");
  78655. if (this._cachedDefines !== join) {
  78656. this._cachedDefines = join;
  78657. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78658. }
  78659. return this._volumetricLightScatteringPass.isReady();
  78660. };
  78661. /**
  78662. * Sets the new light position for light scattering effect
  78663. * @param {BABYLON.Vector3} The new custom light position
  78664. */
  78665. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78666. this.customMeshPosition = position;
  78667. };
  78668. /**
  78669. * Returns the light position for light scattering effect
  78670. * @return {BABYLON.Vector3} The custom light position
  78671. */
  78672. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78673. return this.customMeshPosition;
  78674. };
  78675. /**
  78676. * Disposes the internal assets and detaches the post-process from the camera
  78677. */
  78678. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78679. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78680. if (rttIndex !== -1) {
  78681. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78682. }
  78683. this._volumetricLightScatteringRTT.dispose();
  78684. _super.prototype.dispose.call(this, camera);
  78685. };
  78686. /**
  78687. * Returns the render target texture used by the post-process
  78688. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78689. */
  78690. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78691. return this._volumetricLightScatteringRTT;
  78692. };
  78693. // Private methods
  78694. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78695. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78696. return true;
  78697. }
  78698. return false;
  78699. };
  78700. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78701. var _this = this;
  78702. var engine = scene.getEngine();
  78703. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78704. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78705. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78706. this._volumetricLightScatteringRTT.renderList = null;
  78707. this._volumetricLightScatteringRTT.renderParticles = false;
  78708. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78709. var camera = this.getCamera();
  78710. if (camera) {
  78711. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78712. }
  78713. else {
  78714. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78715. }
  78716. // Custom render function for submeshes
  78717. var renderSubMesh = function (subMesh) {
  78718. var mesh = subMesh.getRenderingMesh();
  78719. if (_this._meshExcluded(mesh)) {
  78720. return;
  78721. }
  78722. var material = subMesh.getMaterial();
  78723. if (!material) {
  78724. return;
  78725. }
  78726. var scene = mesh.getScene();
  78727. var engine = scene.getEngine();
  78728. // Culling
  78729. engine.setState(material.backFaceCulling);
  78730. // Managing instances
  78731. var batch = mesh._getInstancesRenderList(subMesh._id);
  78732. if (batch.mustReturn) {
  78733. return;
  78734. }
  78735. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78736. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78737. var effect = _this._volumetricLightScatteringPass;
  78738. if (mesh === _this.mesh) {
  78739. if (subMesh.effect) {
  78740. effect = subMesh.effect;
  78741. }
  78742. else {
  78743. effect = material.getEffect();
  78744. }
  78745. }
  78746. engine.enableEffect(effect);
  78747. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78748. if (mesh === _this.mesh) {
  78749. material.bind(mesh.getWorldMatrix(), mesh);
  78750. }
  78751. else {
  78752. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78753. // Alpha test
  78754. if (material && material.needAlphaTesting()) {
  78755. var alphaTexture = material.getAlphaTestTexture();
  78756. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78757. if (alphaTexture) {
  78758. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78759. }
  78760. }
  78761. // Bones
  78762. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78763. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78764. }
  78765. }
  78766. // Draw
  78767. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78768. }
  78769. };
  78770. // Render target texture callbacks
  78771. var savedSceneClearColor;
  78772. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78773. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78774. savedSceneClearColor = scene.clearColor;
  78775. scene.clearColor = sceneClearColor;
  78776. });
  78777. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78778. scene.clearColor = savedSceneClearColor;
  78779. });
  78780. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78781. var engine = scene.getEngine();
  78782. var index;
  78783. if (depthOnlySubMeshes.length) {
  78784. engine.setColorWrite(false);
  78785. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78786. renderSubMesh(depthOnlySubMeshes.data[index]);
  78787. }
  78788. engine.setColorWrite(true);
  78789. }
  78790. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78791. renderSubMesh(opaqueSubMeshes.data[index]);
  78792. }
  78793. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78794. renderSubMesh(alphaTestSubMeshes.data[index]);
  78795. }
  78796. if (transparentSubMeshes.length) {
  78797. // Sort sub meshes
  78798. for (index = 0; index < transparentSubMeshes.length; index++) {
  78799. var submesh = transparentSubMeshes.data[index];
  78800. var boundingInfo = submesh.getBoundingInfo();
  78801. if (boundingInfo && scene.activeCamera) {
  78802. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78803. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78804. }
  78805. }
  78806. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78807. sortedArray.sort(function (a, b) {
  78808. // Alpha index first
  78809. if (a._alphaIndex > b._alphaIndex) {
  78810. return 1;
  78811. }
  78812. if (a._alphaIndex < b._alphaIndex) {
  78813. return -1;
  78814. }
  78815. // Then distance to camera
  78816. if (a._distanceToCamera < b._distanceToCamera) {
  78817. return 1;
  78818. }
  78819. if (a._distanceToCamera > b._distanceToCamera) {
  78820. return -1;
  78821. }
  78822. return 0;
  78823. });
  78824. // Render sub meshes
  78825. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78826. for (index = 0; index < sortedArray.length; index++) {
  78827. renderSubMesh(sortedArray[index]);
  78828. }
  78829. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78830. }
  78831. };
  78832. };
  78833. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78834. var transform = scene.getTransformMatrix();
  78835. var meshPosition;
  78836. if (this.useCustomMeshPosition) {
  78837. meshPosition = this.customMeshPosition;
  78838. }
  78839. else if (this.attachedNode) {
  78840. meshPosition = this.attachedNode.position;
  78841. }
  78842. else {
  78843. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78844. }
  78845. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78846. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78847. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78848. if (this.invert)
  78849. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78850. };
  78851. // Static methods
  78852. /**
  78853. * Creates a default mesh for the Volumeric Light Scattering post-process
  78854. * @param {string} The mesh name
  78855. * @param {BABYLON.Scene} The scene where to create the mesh
  78856. * @return {BABYLON.Mesh} the default mesh
  78857. */
  78858. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78859. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78860. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78861. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78862. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78863. mesh.material = material;
  78864. return mesh;
  78865. };
  78866. __decorate([
  78867. BABYLON.serializeAsVector3()
  78868. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78869. __decorate([
  78870. BABYLON.serialize()
  78871. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78872. __decorate([
  78873. BABYLON.serialize()
  78874. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78875. __decorate([
  78876. BABYLON.serializeAsMeshReference()
  78877. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78878. __decorate([
  78879. BABYLON.serialize()
  78880. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78881. __decorate([
  78882. BABYLON.serialize()
  78883. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78884. __decorate([
  78885. BABYLON.serialize()
  78886. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78887. __decorate([
  78888. BABYLON.serialize()
  78889. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78890. __decorate([
  78891. BABYLON.serialize()
  78892. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78893. return VolumetricLightScatteringPostProcess;
  78894. }(BABYLON.PostProcess));
  78895. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78896. })(BABYLON || (BABYLON = {}));
  78897. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78898. //
  78899. // This post-process allows the modification of rendered colors by using
  78900. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78901. //
  78902. // The object needs to be provided an url to a texture containing the color
  78903. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78904. // Use an image editing software to tweak the LUT to match your needs.
  78905. //
  78906. // For an example of a color LUT, see here:
  78907. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78908. // For explanations on color grading, see here:
  78909. // http://udn.epicgames.com/Three/ColorGrading.html
  78910. //
  78911. var BABYLON;
  78912. (function (BABYLON) {
  78913. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78914. __extends(ColorCorrectionPostProcess, _super);
  78915. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78916. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78917. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78918. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78919. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78920. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78921. _this.onApply = function (effect) {
  78922. effect.setTexture("colorTable", _this._colorTableTexture);
  78923. };
  78924. return _this;
  78925. }
  78926. return ColorCorrectionPostProcess;
  78927. }(BABYLON.PostProcess));
  78928. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78929. })(BABYLON || (BABYLON = {}));
  78930. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78931. var BABYLON;
  78932. (function (BABYLON) {
  78933. /** Defines operator used for tonemapping */
  78934. var TonemappingOperator;
  78935. (function (TonemappingOperator) {
  78936. /** Hable */
  78937. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78938. /** Reinhard */
  78939. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78940. /** HejiDawson */
  78941. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78942. /** Photographic */
  78943. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78944. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78945. ;
  78946. /**
  78947. * Defines a post process to apply tone mapping
  78948. */
  78949. var TonemapPostProcess = /** @class */ (function (_super) {
  78950. __extends(TonemapPostProcess, _super);
  78951. /**
  78952. * Creates a new TonemapPostProcess
  78953. * @param name defines the name of the postprocess
  78954. * @param _operator defines the operator to use
  78955. * @param exposureAdjustment defines the required exposure adjustement
  78956. * @param camera defines the camera to use (can be null)
  78957. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78958. * @param engine defines the hosting engine (can be ignore if camera is set)
  78959. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78960. */
  78961. function TonemapPostProcess(name, _operator,
  78962. /** Defines the required exposure adjustement */
  78963. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78965. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78966. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78967. _this._operator = _operator;
  78968. _this.exposureAdjustment = exposureAdjustment;
  78969. var defines = "#define ";
  78970. if (_this._operator === TonemappingOperator.Hable)
  78971. defines += "HABLE_TONEMAPPING";
  78972. else if (_this._operator === TonemappingOperator.Reinhard)
  78973. defines += "REINHARD_TONEMAPPING";
  78974. else if (_this._operator === TonemappingOperator.HejiDawson)
  78975. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78976. else if (_this._operator === TonemappingOperator.Photographic)
  78977. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78978. //sadly a second call to create the effect.
  78979. _this.updateEffect(defines);
  78980. _this.onApply = function (effect) {
  78981. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78982. };
  78983. return _this;
  78984. }
  78985. return TonemapPostProcess;
  78986. }(BABYLON.PostProcess));
  78987. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78988. })(BABYLON || (BABYLON = {}));
  78989. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78990. var BABYLON;
  78991. (function (BABYLON) {
  78992. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78993. __extends(DisplayPassPostProcess, _super);
  78994. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78995. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78996. }
  78997. return DisplayPassPostProcess;
  78998. }(BABYLON.PostProcess));
  78999. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79000. })(BABYLON || (BABYLON = {}));
  79001. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79002. var BABYLON;
  79003. (function (BABYLON) {
  79004. var HighlightsPostProcess = /** @class */ (function (_super) {
  79005. __extends(HighlightsPostProcess, _super);
  79006. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79007. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79008. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79009. }
  79010. return HighlightsPostProcess;
  79011. }(BABYLON.PostProcess));
  79012. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79013. })(BABYLON || (BABYLON = {}));
  79014. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79015. var BABYLON;
  79016. (function (BABYLON) {
  79017. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79018. __extends(ImageProcessingPostProcess, _super);
  79019. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79020. if (camera === void 0) { camera = null; }
  79021. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79022. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79023. _this._fromLinearSpace = true;
  79024. /**
  79025. * Defines cache preventing GC.
  79026. */
  79027. _this._defines = {
  79028. IMAGEPROCESSING: false,
  79029. VIGNETTE: false,
  79030. VIGNETTEBLENDMODEMULTIPLY: false,
  79031. VIGNETTEBLENDMODEOPAQUE: false,
  79032. TONEMAPPING: false,
  79033. CONTRAST: false,
  79034. COLORCURVES: false,
  79035. COLORGRADING: false,
  79036. COLORGRADING3D: false,
  79037. FROMLINEARSPACE: false,
  79038. SAMPLER3DGREENDEPTH: false,
  79039. SAMPLER3DBGRMAP: false,
  79040. IMAGEPROCESSINGPOSTPROCESS: false,
  79041. EXPOSURE: false,
  79042. };
  79043. // Setup the configuration as forced by the constructor. This would then not force the
  79044. // scene materials output in linear space and let untouched the default forward pass.
  79045. if (imageProcessingConfiguration) {
  79046. imageProcessingConfiguration.applyByPostProcess = true;
  79047. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79048. // This will cause the shader to be compiled
  79049. _this.fromLinearSpace = false;
  79050. }
  79051. // Setup the default processing configuration to the scene.
  79052. else {
  79053. _this._attachImageProcessingConfiguration(null, true);
  79054. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79055. }
  79056. _this.onApply = function (effect) {
  79057. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79058. };
  79059. return _this;
  79060. }
  79061. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79062. /**
  79063. * Gets the image processing configuration used either in this material.
  79064. */
  79065. get: function () {
  79066. return this._imageProcessingConfiguration;
  79067. },
  79068. /**
  79069. * Sets the Default image processing configuration used either in the this material.
  79070. *
  79071. * If sets to null, the scene one is in use.
  79072. */
  79073. set: function (value) {
  79074. this._attachImageProcessingConfiguration(value);
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. /**
  79080. * Attaches a new image processing configuration to the PBR Material.
  79081. * @param configuration
  79082. */
  79083. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79084. var _this = this;
  79085. if (doNotBuild === void 0) { doNotBuild = false; }
  79086. if (configuration === this._imageProcessingConfiguration) {
  79087. return;
  79088. }
  79089. // Detaches observer.
  79090. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79091. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79092. }
  79093. // Pick the scene configuration if needed.
  79094. if (!configuration) {
  79095. var scene = null;
  79096. var engine = this.getEngine();
  79097. var camera = this.getCamera();
  79098. if (camera) {
  79099. scene = camera.getScene();
  79100. }
  79101. else if (engine && engine.scenes) {
  79102. var scenes = engine.scenes;
  79103. scene = scenes[scenes.length - 1];
  79104. }
  79105. else {
  79106. scene = BABYLON.Engine.LastCreatedScene;
  79107. }
  79108. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79109. }
  79110. else {
  79111. this._imageProcessingConfiguration = configuration;
  79112. }
  79113. // Attaches observer.
  79114. if (this._imageProcessingConfiguration) {
  79115. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79116. _this._updateParameters();
  79117. });
  79118. }
  79119. // Ensure the effect will be rebuilt.
  79120. if (!doNotBuild) {
  79121. this._updateParameters();
  79122. }
  79123. };
  79124. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79125. /**
  79126. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79127. */
  79128. get: function () {
  79129. return this.imageProcessingConfiguration.colorCurves;
  79130. },
  79131. /**
  79132. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79133. */
  79134. set: function (value) {
  79135. this.imageProcessingConfiguration.colorCurves = value;
  79136. },
  79137. enumerable: true,
  79138. configurable: true
  79139. });
  79140. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79141. /**
  79142. * Gets wether the color curves effect is enabled.
  79143. */
  79144. get: function () {
  79145. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79146. },
  79147. /**
  79148. * Sets wether the color curves effect is enabled.
  79149. */
  79150. set: function (value) {
  79151. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79152. },
  79153. enumerable: true,
  79154. configurable: true
  79155. });
  79156. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79157. /**
  79158. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79159. */
  79160. get: function () {
  79161. return this.imageProcessingConfiguration.colorGradingTexture;
  79162. },
  79163. /**
  79164. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79165. */
  79166. set: function (value) {
  79167. this.imageProcessingConfiguration.colorGradingTexture = value;
  79168. },
  79169. enumerable: true,
  79170. configurable: true
  79171. });
  79172. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79173. /**
  79174. * Gets wether the color grading effect is enabled.
  79175. */
  79176. get: function () {
  79177. return this.imageProcessingConfiguration.colorGradingEnabled;
  79178. },
  79179. /**
  79180. * Gets wether the color grading effect is enabled.
  79181. */
  79182. set: function (value) {
  79183. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79184. },
  79185. enumerable: true,
  79186. configurable: true
  79187. });
  79188. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79189. /**
  79190. * Gets exposure used in the effect.
  79191. */
  79192. get: function () {
  79193. return this.imageProcessingConfiguration.exposure;
  79194. },
  79195. /**
  79196. * Sets exposure used in the effect.
  79197. */
  79198. set: function (value) {
  79199. this.imageProcessingConfiguration.exposure = value;
  79200. },
  79201. enumerable: true,
  79202. configurable: true
  79203. });
  79204. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79205. /**
  79206. * Gets wether tonemapping is enabled or not.
  79207. */
  79208. get: function () {
  79209. return this._imageProcessingConfiguration.toneMappingEnabled;
  79210. },
  79211. /**
  79212. * Sets wether tonemapping is enabled or not
  79213. */
  79214. set: function (value) {
  79215. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79216. },
  79217. enumerable: true,
  79218. configurable: true
  79219. });
  79220. ;
  79221. ;
  79222. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79223. /**
  79224. * Gets contrast used in the effect.
  79225. */
  79226. get: function () {
  79227. return this.imageProcessingConfiguration.contrast;
  79228. },
  79229. /**
  79230. * Sets contrast used in the effect.
  79231. */
  79232. set: function (value) {
  79233. this.imageProcessingConfiguration.contrast = value;
  79234. },
  79235. enumerable: true,
  79236. configurable: true
  79237. });
  79238. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79239. /**
  79240. * Gets Vignette stretch size.
  79241. */
  79242. get: function () {
  79243. return this.imageProcessingConfiguration.vignetteStretch;
  79244. },
  79245. /**
  79246. * Sets Vignette stretch size.
  79247. */
  79248. set: function (value) {
  79249. this.imageProcessingConfiguration.vignetteStretch = value;
  79250. },
  79251. enumerable: true,
  79252. configurable: true
  79253. });
  79254. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79255. /**
  79256. * Gets Vignette centre X Offset.
  79257. */
  79258. get: function () {
  79259. return this.imageProcessingConfiguration.vignetteCentreX;
  79260. },
  79261. /**
  79262. * Sets Vignette centre X Offset.
  79263. */
  79264. set: function (value) {
  79265. this.imageProcessingConfiguration.vignetteCentreX = value;
  79266. },
  79267. enumerable: true,
  79268. configurable: true
  79269. });
  79270. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79271. /**
  79272. * Gets Vignette centre Y Offset.
  79273. */
  79274. get: function () {
  79275. return this.imageProcessingConfiguration.vignetteCentreY;
  79276. },
  79277. /**
  79278. * Sets Vignette centre Y Offset.
  79279. */
  79280. set: function (value) {
  79281. this.imageProcessingConfiguration.vignetteCentreY = value;
  79282. },
  79283. enumerable: true,
  79284. configurable: true
  79285. });
  79286. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79287. /**
  79288. * Gets Vignette weight or intensity of the vignette effect.
  79289. */
  79290. get: function () {
  79291. return this.imageProcessingConfiguration.vignetteWeight;
  79292. },
  79293. /**
  79294. * Sets Vignette weight or intensity of the vignette effect.
  79295. */
  79296. set: function (value) {
  79297. this.imageProcessingConfiguration.vignetteWeight = value;
  79298. },
  79299. enumerable: true,
  79300. configurable: true
  79301. });
  79302. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79303. /**
  79304. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79305. * if vignetteEnabled is set to true.
  79306. */
  79307. get: function () {
  79308. return this.imageProcessingConfiguration.vignetteColor;
  79309. },
  79310. /**
  79311. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79312. * if vignetteEnabled is set to true.
  79313. */
  79314. set: function (value) {
  79315. this.imageProcessingConfiguration.vignetteColor = value;
  79316. },
  79317. enumerable: true,
  79318. configurable: true
  79319. });
  79320. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79321. /**
  79322. * Gets Camera field of view used by the Vignette effect.
  79323. */
  79324. get: function () {
  79325. return this.imageProcessingConfiguration.vignetteCameraFov;
  79326. },
  79327. /**
  79328. * Sets Camera field of view used by the Vignette effect.
  79329. */
  79330. set: function (value) {
  79331. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79332. },
  79333. enumerable: true,
  79334. configurable: true
  79335. });
  79336. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79337. /**
  79338. * Gets the vignette blend mode allowing different kind of effect.
  79339. */
  79340. get: function () {
  79341. return this.imageProcessingConfiguration.vignetteBlendMode;
  79342. },
  79343. /**
  79344. * Sets the vignette blend mode allowing different kind of effect.
  79345. */
  79346. set: function (value) {
  79347. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79348. },
  79349. enumerable: true,
  79350. configurable: true
  79351. });
  79352. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79353. /**
  79354. * Gets wether the vignette effect is enabled.
  79355. */
  79356. get: function () {
  79357. return this.imageProcessingConfiguration.vignetteEnabled;
  79358. },
  79359. /**
  79360. * Sets wether the vignette effect is enabled.
  79361. */
  79362. set: function (value) {
  79363. this.imageProcessingConfiguration.vignetteEnabled = value;
  79364. },
  79365. enumerable: true,
  79366. configurable: true
  79367. });
  79368. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79369. /**
  79370. * Gets wether the input of the processing is in Gamma or Linear Space.
  79371. */
  79372. get: function () {
  79373. return this._fromLinearSpace;
  79374. },
  79375. /**
  79376. * Sets wether the input of the processing is in Gamma or Linear Space.
  79377. */
  79378. set: function (value) {
  79379. if (this._fromLinearSpace === value) {
  79380. return;
  79381. }
  79382. this._fromLinearSpace = value;
  79383. this._updateParameters();
  79384. },
  79385. enumerable: true,
  79386. configurable: true
  79387. });
  79388. ImageProcessingPostProcess.prototype.getClassName = function () {
  79389. return "ImageProcessingPostProcess";
  79390. };
  79391. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79392. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79393. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79394. var defines = "";
  79395. for (var define in this._defines) {
  79396. if (this._defines[define]) {
  79397. defines += "#define " + define + ";\r\n";
  79398. }
  79399. }
  79400. var samplers = ["textureSampler"];
  79401. var uniforms = ["scale"];
  79402. if (BABYLON.ImageProcessingConfiguration) {
  79403. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79404. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79405. }
  79406. this.updateEffect(defines, uniforms, samplers);
  79407. };
  79408. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79409. _super.prototype.dispose.call(this, camera);
  79410. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79411. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79412. }
  79413. if (this._imageProcessingConfiguration) {
  79414. this.imageProcessingConfiguration.applyByPostProcess = false;
  79415. }
  79416. };
  79417. __decorate([
  79418. BABYLON.serialize()
  79419. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79420. return ImageProcessingPostProcess;
  79421. }(BABYLON.PostProcess));
  79422. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79423. })(BABYLON || (BABYLON = {}));
  79424. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79425. var BABYLON;
  79426. (function (BABYLON) {
  79427. /**
  79428. * Class used to store bone information
  79429. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79430. */
  79431. var Bone = /** @class */ (function (_super) {
  79432. __extends(Bone, _super);
  79433. /**
  79434. * Create a new bone
  79435. * @param name defines the bone name
  79436. * @param skeleton defines the parent skeleton
  79437. * @param parentBone defines the parent (can be null if the bone is the root)
  79438. * @param localMatrix defines the local matrix
  79439. * @param restPose defines the rest pose matrix
  79440. * @param baseMatrix defines the base matrix
  79441. * @param index defines index of the bone in the hiearchy
  79442. */
  79443. function Bone(
  79444. /**
  79445. * defines the bone name
  79446. */
  79447. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79448. if (parentBone === void 0) { parentBone = null; }
  79449. if (localMatrix === void 0) { localMatrix = null; }
  79450. if (restPose === void 0) { restPose = null; }
  79451. if (baseMatrix === void 0) { baseMatrix = null; }
  79452. if (index === void 0) { index = null; }
  79453. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79454. _this.name = name;
  79455. /**
  79456. * Gets the list of child bones
  79457. */
  79458. _this.children = new Array();
  79459. /** Gets the animations associated with this bone */
  79460. _this.animations = new Array();
  79461. /**
  79462. * @hidden Internal only
  79463. * Set this value to map this bone to a different index in the transform matrices
  79464. * Set this value to -1 to exclude the bone from the transform matrices
  79465. */
  79466. _this._index = null;
  79467. _this._absoluteTransform = new BABYLON.Matrix();
  79468. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79469. _this._scalingDeterminant = 1;
  79470. _this._worldTransform = new BABYLON.Matrix();
  79471. _this._needToDecompose = true;
  79472. _this._needToCompose = false;
  79473. _this._skeleton = skeleton;
  79474. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79475. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79476. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79477. _this._index = index;
  79478. skeleton.bones.push(_this);
  79479. _this.setParent(parentBone, false);
  79480. if (baseMatrix || localMatrix) {
  79481. _this._updateDifferenceMatrix();
  79482. }
  79483. return _this;
  79484. }
  79485. Object.defineProperty(Bone.prototype, "_matrix", {
  79486. /** @hidden */
  79487. get: function () {
  79488. this._compose();
  79489. return this._localMatrix;
  79490. },
  79491. /** @hidden */
  79492. set: function (value) {
  79493. this._localMatrix.copyFrom(value);
  79494. this._needToDecompose = true;
  79495. },
  79496. enumerable: true,
  79497. configurable: true
  79498. });
  79499. // Members
  79500. /**
  79501. * Gets the parent skeleton
  79502. * @returns a skeleton
  79503. */
  79504. Bone.prototype.getSkeleton = function () {
  79505. return this._skeleton;
  79506. };
  79507. /**
  79508. * Gets parent bone
  79509. * @returns a bone or null if the bone is the root of the bone hierarchy
  79510. */
  79511. Bone.prototype.getParent = function () {
  79512. return this._parent;
  79513. };
  79514. /**
  79515. * Sets the parent bone
  79516. * @param parent defines the parent (can be null if the bone is the root)
  79517. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79518. */
  79519. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79520. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79521. if (this._parent === parent) {
  79522. return;
  79523. }
  79524. if (this._parent) {
  79525. var index = this._parent.children.indexOf(this);
  79526. if (index !== -1) {
  79527. this._parent.children.splice(index, 1);
  79528. }
  79529. }
  79530. this._parent = parent;
  79531. if (this._parent) {
  79532. this._parent.children.push(this);
  79533. }
  79534. if (updateDifferenceMatrix) {
  79535. this._updateDifferenceMatrix();
  79536. }
  79537. this.markAsDirty();
  79538. };
  79539. /**
  79540. * Gets the local matrix
  79541. * @returns a matrix
  79542. */
  79543. Bone.prototype.getLocalMatrix = function () {
  79544. this._compose();
  79545. return this._localMatrix;
  79546. };
  79547. /**
  79548. * Gets the base matrix (initial matrix which remains unchanged)
  79549. * @returns a matrix
  79550. */
  79551. Bone.prototype.getBaseMatrix = function () {
  79552. return this._baseMatrix;
  79553. };
  79554. /**
  79555. * Gets the rest pose matrix
  79556. * @returns a matrix
  79557. */
  79558. Bone.prototype.getRestPose = function () {
  79559. return this._restPose;
  79560. };
  79561. /**
  79562. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79563. */
  79564. Bone.prototype.getWorldMatrix = function () {
  79565. return this._worldTransform;
  79566. };
  79567. /**
  79568. * Sets the local matrix to rest pose matrix
  79569. */
  79570. Bone.prototype.returnToRest = function () {
  79571. this.updateMatrix(this._restPose.clone());
  79572. };
  79573. /**
  79574. * Gets the inverse of the absolute transform matrix.
  79575. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79576. * @returns a matrix
  79577. */
  79578. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79579. return this._invertedAbsoluteTransform;
  79580. };
  79581. /**
  79582. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79583. * @returns a matrix
  79584. */
  79585. Bone.prototype.getAbsoluteTransform = function () {
  79586. return this._absoluteTransform;
  79587. };
  79588. Object.defineProperty(Bone.prototype, "position", {
  79589. // Properties (matches AbstractMesh properties)
  79590. /** Gets or sets current position (in local space) */
  79591. get: function () {
  79592. this._decompose();
  79593. return this._localPosition;
  79594. },
  79595. set: function (newPosition) {
  79596. this._decompose();
  79597. this._localPosition.copyFrom(newPosition);
  79598. this._markAsDirtyAndCompose();
  79599. },
  79600. enumerable: true,
  79601. configurable: true
  79602. });
  79603. Object.defineProperty(Bone.prototype, "rotation", {
  79604. /** Gets or sets current rotation (in local space) */
  79605. get: function () {
  79606. return this.getRotation();
  79607. },
  79608. set: function (newRotation) {
  79609. this.setRotation(newRotation);
  79610. },
  79611. enumerable: true,
  79612. configurable: true
  79613. });
  79614. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79615. /** Gets or sets current rotation quaternion (in local space) */
  79616. get: function () {
  79617. this._decompose();
  79618. return this._localRotation;
  79619. },
  79620. set: function (newRotation) {
  79621. this.setRotationQuaternion(newRotation);
  79622. },
  79623. enumerable: true,
  79624. configurable: true
  79625. });
  79626. Object.defineProperty(Bone.prototype, "scaling", {
  79627. /** Gets or sets current scaling (in local space) */
  79628. get: function () {
  79629. return this.getScale();
  79630. },
  79631. set: function (newScaling) {
  79632. this.setScale(newScaling);
  79633. },
  79634. enumerable: true,
  79635. configurable: true
  79636. });
  79637. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79638. /**
  79639. * Gets the animation properties override
  79640. */
  79641. get: function () {
  79642. return this._skeleton.animationPropertiesOverride;
  79643. },
  79644. enumerable: true,
  79645. configurable: true
  79646. });
  79647. // Methods
  79648. Bone.prototype._decompose = function () {
  79649. if (!this._needToDecompose) {
  79650. return;
  79651. }
  79652. this._needToDecompose = false;
  79653. if (!this._localScaling) {
  79654. this._localScaling = BABYLON.Vector3.Zero();
  79655. this._localRotation = BABYLON.Quaternion.Zero();
  79656. this._localPosition = BABYLON.Vector3.Zero();
  79657. }
  79658. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79659. };
  79660. Bone.prototype._compose = function () {
  79661. if (!this._needToCompose) {
  79662. return;
  79663. }
  79664. this._needToCompose = false;
  79665. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79666. };
  79667. /**
  79668. * Update the base and local matrices
  79669. * @param matrix defines the new base or local matrix
  79670. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79671. * @param updateLocalMatrix defines if the local matrix should be updated
  79672. */
  79673. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79674. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79675. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79676. this._baseMatrix.copyFrom(matrix);
  79677. if (updateDifferenceMatrix) {
  79678. this._updateDifferenceMatrix();
  79679. }
  79680. if (updateLocalMatrix) {
  79681. this._localMatrix.copyFrom(matrix);
  79682. this._markAsDirtyAndDecompose();
  79683. }
  79684. else {
  79685. this.markAsDirty();
  79686. }
  79687. };
  79688. /** @hidden */
  79689. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79690. if (updateChildren === void 0) { updateChildren = true; }
  79691. if (!rootMatrix) {
  79692. rootMatrix = this._baseMatrix;
  79693. }
  79694. if (this._parent) {
  79695. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79696. }
  79697. else {
  79698. this._absoluteTransform.copyFrom(rootMatrix);
  79699. }
  79700. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79701. if (updateChildren) {
  79702. for (var index = 0; index < this.children.length; index++) {
  79703. this.children[index]._updateDifferenceMatrix();
  79704. }
  79705. }
  79706. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79707. };
  79708. /**
  79709. * Flag the bone as dirty (Forcing it to update everything)
  79710. */
  79711. Bone.prototype.markAsDirty = function () {
  79712. this._currentRenderId++;
  79713. this._childRenderId++;
  79714. this._skeleton._markAsDirty();
  79715. };
  79716. Bone.prototype._markAsDirtyAndCompose = function () {
  79717. this.markAsDirty();
  79718. this._needToCompose = true;
  79719. };
  79720. Bone.prototype._markAsDirtyAndDecompose = function () {
  79721. this.markAsDirty();
  79722. this._needToDecompose = true;
  79723. };
  79724. /**
  79725. * Copy an animation range from another bone
  79726. * @param source defines the source bone
  79727. * @param rangeName defines the range name to copy
  79728. * @param frameOffset defines the frame offset
  79729. * @param rescaleAsRequired defines if rescaling must be applied if required
  79730. * @param skelDimensionsRatio defines the scaling ratio
  79731. * @returns true if operation was successful
  79732. */
  79733. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79734. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79735. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79736. // all animation may be coming from a library skeleton, so may need to create animation
  79737. if (this.animations.length === 0) {
  79738. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79739. this.animations[0].setKeys([]);
  79740. }
  79741. // get animation info / verify there is such a range from the source bone
  79742. var sourceRange = source.animations[0].getRange(rangeName);
  79743. if (!sourceRange) {
  79744. return false;
  79745. }
  79746. var from = sourceRange.from;
  79747. var to = sourceRange.to;
  79748. var sourceKeys = source.animations[0].getKeys();
  79749. // rescaling prep
  79750. var sourceBoneLength = source.length;
  79751. var sourceParent = source.getParent();
  79752. var parent = this.getParent();
  79753. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79754. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79755. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79756. var destKeys = this.animations[0].getKeys();
  79757. // loop vars declaration
  79758. var orig;
  79759. var origTranslation;
  79760. var mat;
  79761. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79762. orig = sourceKeys[key];
  79763. if (orig.frame >= from && orig.frame <= to) {
  79764. if (rescaleAsRequired) {
  79765. mat = orig.value.clone();
  79766. // scale based on parent ratio, when bone has parent
  79767. if (parentScalingReqd) {
  79768. origTranslation = mat.getTranslation();
  79769. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79770. // scale based on skeleton dimension ratio when root bone, and value is passed
  79771. }
  79772. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79773. origTranslation = mat.getTranslation();
  79774. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79775. // use original when root bone, and no data for skelDimensionsRatio
  79776. }
  79777. else {
  79778. mat = orig.value;
  79779. }
  79780. }
  79781. else {
  79782. mat = orig.value;
  79783. }
  79784. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79785. }
  79786. }
  79787. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79788. return true;
  79789. };
  79790. /**
  79791. * Translate the bone in local or world space
  79792. * @param vec The amount to translate the bone
  79793. * @param space The space that the translation is in
  79794. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79795. */
  79796. Bone.prototype.translate = function (vec, space, mesh) {
  79797. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79798. var lm = this.getLocalMatrix();
  79799. if (space == BABYLON.Space.LOCAL) {
  79800. lm.m[12] += vec.x;
  79801. lm.m[13] += vec.y;
  79802. lm.m[14] += vec.z;
  79803. }
  79804. else {
  79805. var wm = null;
  79806. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79807. if (mesh) {
  79808. wm = mesh.getWorldMatrix();
  79809. }
  79810. this._skeleton.computeAbsoluteTransforms();
  79811. var tmat = Bone._tmpMats[0];
  79812. var tvec = Bone._tmpVecs[0];
  79813. if (this._parent) {
  79814. if (mesh && wm) {
  79815. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79816. tmat.multiplyToRef(wm, tmat);
  79817. }
  79818. else {
  79819. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79820. }
  79821. }
  79822. tmat.m[12] = 0;
  79823. tmat.m[13] = 0;
  79824. tmat.m[14] = 0;
  79825. tmat.invert();
  79826. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79827. lm.m[12] += tvec.x;
  79828. lm.m[13] += tvec.y;
  79829. lm.m[14] += tvec.z;
  79830. }
  79831. this._markAsDirtyAndDecompose();
  79832. };
  79833. /**
  79834. * Set the postion of the bone in local or world space
  79835. * @param position The position to set the bone
  79836. * @param space The space that the position is in
  79837. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79838. */
  79839. Bone.prototype.setPosition = function (position, space, mesh) {
  79840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79841. var lm = this.getLocalMatrix();
  79842. if (space == BABYLON.Space.LOCAL) {
  79843. lm.m[12] = position.x;
  79844. lm.m[13] = position.y;
  79845. lm.m[14] = position.z;
  79846. }
  79847. else {
  79848. var wm = null;
  79849. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79850. if (mesh) {
  79851. wm = mesh.getWorldMatrix();
  79852. }
  79853. this._skeleton.computeAbsoluteTransforms();
  79854. var tmat = Bone._tmpMats[0];
  79855. var vec = Bone._tmpVecs[0];
  79856. if (this._parent) {
  79857. if (mesh && wm) {
  79858. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79859. tmat.multiplyToRef(wm, tmat);
  79860. }
  79861. else {
  79862. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79863. }
  79864. }
  79865. tmat.invert();
  79866. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79867. lm.m[12] = vec.x;
  79868. lm.m[13] = vec.y;
  79869. lm.m[14] = vec.z;
  79870. }
  79871. this._markAsDirtyAndDecompose();
  79872. };
  79873. /**
  79874. * Set the absolute position of the bone (world space)
  79875. * @param position The position to set the bone
  79876. * @param mesh The mesh that this bone is attached to
  79877. */
  79878. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79879. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79880. };
  79881. /**
  79882. * Scale the bone on the x, y and z axes (in local space)
  79883. * @param x The amount to scale the bone on the x axis
  79884. * @param y The amount to scale the bone on the y axis
  79885. * @param z The amount to scale the bone on the z axis
  79886. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79887. */
  79888. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79889. if (scaleChildren === void 0) { scaleChildren = false; }
  79890. var locMat = this.getLocalMatrix();
  79891. // Apply new scaling on top of current local matrix
  79892. var scaleMat = Bone._tmpMats[0];
  79893. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79894. scaleMat.multiplyToRef(locMat, locMat);
  79895. // Invert scaling matrix and apply the inverse to all children
  79896. scaleMat.invert();
  79897. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79898. var child = _a[_i];
  79899. var cm = child.getLocalMatrix();
  79900. cm.multiplyToRef(scaleMat, cm);
  79901. cm.m[12] *= x;
  79902. cm.m[13] *= y;
  79903. cm.m[14] *= z;
  79904. child._markAsDirtyAndDecompose();
  79905. }
  79906. this._markAsDirtyAndDecompose();
  79907. if (scaleChildren) {
  79908. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79909. var child = _c[_b];
  79910. child.scale(x, y, z, scaleChildren);
  79911. }
  79912. }
  79913. };
  79914. /**
  79915. * Set the bone scaling in local space
  79916. * @param scale defines the scaling vector
  79917. */
  79918. Bone.prototype.setScale = function (scale) {
  79919. this._decompose();
  79920. this._localScaling.copyFrom(scale);
  79921. this._markAsDirtyAndCompose();
  79922. };
  79923. /**
  79924. * Gets the current scaling in local space
  79925. * @returns the current scaling vector
  79926. */
  79927. Bone.prototype.getScale = function () {
  79928. this._decompose();
  79929. return this._localScaling;
  79930. };
  79931. /**
  79932. * Gets the current scaling in local space and stores it in a target vector
  79933. * @param result defines the target vector
  79934. */
  79935. Bone.prototype.getScaleToRef = function (result) {
  79936. this._decompose();
  79937. result.copyFrom(this._localScaling);
  79938. };
  79939. /**
  79940. * Set the yaw, pitch, and roll of the bone in local or world space
  79941. * @param yaw The rotation of the bone on the y axis
  79942. * @param pitch The rotation of the bone on the x axis
  79943. * @param roll The rotation of the bone on the z axis
  79944. * @param space The space that the axes of rotation are in
  79945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79946. */
  79947. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79949. if (space === BABYLON.Space.LOCAL) {
  79950. var quat = Bone._tmpQuat;
  79951. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79952. this.setRotationQuaternion(quat, space, mesh);
  79953. return;
  79954. }
  79955. var rotMatInv = Bone._tmpMats[0];
  79956. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79957. return;
  79958. }
  79959. var rotMat = Bone._tmpMats[1];
  79960. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79961. rotMatInv.multiplyToRef(rotMat, rotMat);
  79962. this._rotateWithMatrix(rotMat, space, mesh);
  79963. };
  79964. /**
  79965. * Add a rotation to the bone on an axis in local or world space
  79966. * @param axis The axis to rotate the bone on
  79967. * @param amount The amount to rotate the bone
  79968. * @param space The space that the axis is in
  79969. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79970. */
  79971. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79973. var rmat = Bone._tmpMats[0];
  79974. rmat.m[12] = 0;
  79975. rmat.m[13] = 0;
  79976. rmat.m[14] = 0;
  79977. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79978. this._rotateWithMatrix(rmat, space, mesh);
  79979. };
  79980. /**
  79981. * Set the rotation of the bone to a particular axis angle in local or world space
  79982. * @param axis The axis to rotate the bone on
  79983. * @param angle The angle that the bone should be rotated to
  79984. * @param space The space that the axis is in
  79985. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79986. */
  79987. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79989. if (space === BABYLON.Space.LOCAL) {
  79990. var quat = Bone._tmpQuat;
  79991. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79992. this.setRotationQuaternion(quat, space, mesh);
  79993. return;
  79994. }
  79995. var rotMatInv = Bone._tmpMats[0];
  79996. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79997. return;
  79998. }
  79999. var rotMat = Bone._tmpMats[1];
  80000. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80001. rotMatInv.multiplyToRef(rotMat, rotMat);
  80002. this._rotateWithMatrix(rotMat, space, mesh);
  80003. };
  80004. /**
  80005. * Set the euler rotation of the bone in local of world space
  80006. * @param rotation The euler rotation that the bone should be set to
  80007. * @param space The space that the rotation is in
  80008. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80009. */
  80010. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80012. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80013. };
  80014. /**
  80015. * Set the quaternion rotation of the bone in local of world space
  80016. * @param quat The quaternion rotation that the bone should be set to
  80017. * @param space The space that the rotation is in
  80018. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80019. */
  80020. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80021. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80022. if (space === BABYLON.Space.LOCAL) {
  80023. this._decompose();
  80024. this._localRotation.copyFrom(quat);
  80025. this._markAsDirtyAndCompose();
  80026. return;
  80027. }
  80028. var rotMatInv = Bone._tmpMats[0];
  80029. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80030. return;
  80031. }
  80032. var rotMat = Bone._tmpMats[1];
  80033. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80034. rotMatInv.multiplyToRef(rotMat, rotMat);
  80035. this._rotateWithMatrix(rotMat, space, mesh);
  80036. };
  80037. /**
  80038. * Set the rotation matrix of the bone in local of world space
  80039. * @param rotMat The rotation matrix that the bone should be set to
  80040. * @param space The space that the rotation is in
  80041. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80042. */
  80043. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80045. if (space === BABYLON.Space.LOCAL) {
  80046. var quat = Bone._tmpQuat;
  80047. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80048. this.setRotationQuaternion(quat, space, mesh);
  80049. return;
  80050. }
  80051. var rotMatInv = Bone._tmpMats[0];
  80052. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80053. return;
  80054. }
  80055. var rotMat2 = Bone._tmpMats[1];
  80056. rotMat2.copyFrom(rotMat);
  80057. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80058. this._rotateWithMatrix(rotMat2, space, mesh);
  80059. };
  80060. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80062. var lmat = this.getLocalMatrix();
  80063. var lx = lmat.m[12];
  80064. var ly = lmat.m[13];
  80065. var lz = lmat.m[14];
  80066. var parent = this.getParent();
  80067. var parentScale = Bone._tmpMats[3];
  80068. var parentScaleInv = Bone._tmpMats[4];
  80069. if (parent && space == BABYLON.Space.WORLD) {
  80070. if (mesh) {
  80071. parentScale.copyFrom(mesh.getWorldMatrix());
  80072. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80073. }
  80074. else {
  80075. parentScale.copyFrom(parent.getAbsoluteTransform());
  80076. }
  80077. parentScaleInv.copyFrom(parentScale);
  80078. parentScaleInv.invert();
  80079. lmat.multiplyToRef(parentScale, lmat);
  80080. lmat.multiplyToRef(rmat, lmat);
  80081. lmat.multiplyToRef(parentScaleInv, lmat);
  80082. }
  80083. else {
  80084. if (space == BABYLON.Space.WORLD && mesh) {
  80085. parentScale.copyFrom(mesh.getWorldMatrix());
  80086. parentScaleInv.copyFrom(parentScale);
  80087. parentScaleInv.invert();
  80088. lmat.multiplyToRef(parentScale, lmat);
  80089. lmat.multiplyToRef(rmat, lmat);
  80090. lmat.multiplyToRef(parentScaleInv, lmat);
  80091. }
  80092. else {
  80093. lmat.multiplyToRef(rmat, lmat);
  80094. }
  80095. }
  80096. lmat.m[12] = lx;
  80097. lmat.m[13] = ly;
  80098. lmat.m[14] = lz;
  80099. this.computeAbsoluteTransforms();
  80100. this._markAsDirtyAndDecompose();
  80101. };
  80102. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80103. var scaleMatrix = Bone._tmpMats[2];
  80104. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80105. if (mesh) {
  80106. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80107. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80108. }
  80109. rotMatInv.invert();
  80110. if (isNaN(rotMatInv.m[0])) {
  80111. // Matrix failed to invert.
  80112. // This can happen if scale is zero for example.
  80113. return false;
  80114. }
  80115. scaleMatrix.m[0] *= this._scalingDeterminant;
  80116. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80117. return true;
  80118. };
  80119. /**
  80120. * Get the position of the bone in local or world space
  80121. * @param space The space that the returned position is in
  80122. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80123. * @returns The position of the bone
  80124. */
  80125. Bone.prototype.getPosition = function (space, mesh) {
  80126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80127. if (mesh === void 0) { mesh = null; }
  80128. var pos = BABYLON.Vector3.Zero();
  80129. this.getPositionToRef(space, mesh, pos);
  80130. return pos;
  80131. };
  80132. /**
  80133. * Copy the position of the bone to a vector3 in local or world space
  80134. * @param space The space that the returned position is in
  80135. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80136. * @param result The vector3 to copy the position to
  80137. */
  80138. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80139. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80140. if (space == BABYLON.Space.LOCAL) {
  80141. var lm = this.getLocalMatrix();
  80142. result.x = lm.m[12];
  80143. result.y = lm.m[13];
  80144. result.z = lm.m[14];
  80145. }
  80146. else {
  80147. var wm = null;
  80148. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80149. if (mesh) {
  80150. wm = mesh.getWorldMatrix();
  80151. }
  80152. this._skeleton.computeAbsoluteTransforms();
  80153. var tmat = Bone._tmpMats[0];
  80154. if (mesh && wm) {
  80155. tmat.copyFrom(this.getAbsoluteTransform());
  80156. tmat.multiplyToRef(wm, tmat);
  80157. }
  80158. else {
  80159. tmat = this.getAbsoluteTransform();
  80160. }
  80161. result.x = tmat.m[12];
  80162. result.y = tmat.m[13];
  80163. result.z = tmat.m[14];
  80164. }
  80165. };
  80166. /**
  80167. * Get the absolute position of the bone (world space)
  80168. * @param mesh The mesh that this bone is attached to
  80169. * @returns The absolute position of the bone
  80170. */
  80171. Bone.prototype.getAbsolutePosition = function (mesh) {
  80172. if (mesh === void 0) { mesh = null; }
  80173. var pos = BABYLON.Vector3.Zero();
  80174. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80175. return pos;
  80176. };
  80177. /**
  80178. * Copy the absolute position of the bone (world space) to the result param
  80179. * @param mesh The mesh that this bone is attached to
  80180. * @param result The vector3 to copy the absolute position to
  80181. */
  80182. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80183. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80184. };
  80185. /**
  80186. * Compute the absolute transforms of this bone and its children
  80187. */
  80188. Bone.prototype.computeAbsoluteTransforms = function () {
  80189. this._compose();
  80190. if (this._parent) {
  80191. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80192. }
  80193. else {
  80194. this._absoluteTransform.copyFrom(this._localMatrix);
  80195. var poseMatrix = this._skeleton.getPoseMatrix();
  80196. if (poseMatrix) {
  80197. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80198. }
  80199. }
  80200. var children = this.children;
  80201. var len = children.length;
  80202. for (var i = 0; i < len; i++) {
  80203. children[i].computeAbsoluteTransforms();
  80204. }
  80205. };
  80206. /**
  80207. * Get the world direction from an axis that is in the local space of the bone
  80208. * @param localAxis The local direction that is used to compute the world direction
  80209. * @param mesh The mesh that this bone is attached to
  80210. * @returns The world direction
  80211. */
  80212. Bone.prototype.getDirection = function (localAxis, mesh) {
  80213. if (mesh === void 0) { mesh = null; }
  80214. var result = BABYLON.Vector3.Zero();
  80215. this.getDirectionToRef(localAxis, mesh, result);
  80216. return result;
  80217. };
  80218. /**
  80219. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80220. * @param localAxis The local direction that is used to compute the world direction
  80221. * @param mesh The mesh that this bone is attached to
  80222. * @param result The vector3 that the world direction will be copied to
  80223. */
  80224. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80225. if (mesh === void 0) { mesh = null; }
  80226. var wm = null;
  80227. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80228. if (mesh) {
  80229. wm = mesh.getWorldMatrix();
  80230. }
  80231. this._skeleton.computeAbsoluteTransforms();
  80232. var mat = Bone._tmpMats[0];
  80233. mat.copyFrom(this.getAbsoluteTransform());
  80234. if (mesh && wm) {
  80235. mat.multiplyToRef(wm, mat);
  80236. }
  80237. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80238. result.normalize();
  80239. };
  80240. /**
  80241. * Get the euler rotation of the bone in local or world space
  80242. * @param space The space that the rotation should be in
  80243. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80244. * @returns The euler rotation
  80245. */
  80246. Bone.prototype.getRotation = function (space, mesh) {
  80247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80248. if (mesh === void 0) { mesh = null; }
  80249. var result = BABYLON.Vector3.Zero();
  80250. this.getRotationToRef(space, mesh, result);
  80251. return result;
  80252. };
  80253. /**
  80254. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80255. * @param space The space that the rotation should be in
  80256. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80257. * @param result The vector3 that the rotation should be copied to
  80258. */
  80259. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80261. if (mesh === void 0) { mesh = null; }
  80262. var quat = Bone._tmpQuat;
  80263. this.getRotationQuaternionToRef(space, mesh, quat);
  80264. quat.toEulerAnglesToRef(result);
  80265. };
  80266. /**
  80267. * Get the quaternion rotation of the bone in either local or world space
  80268. * @param space The space that the rotation should be in
  80269. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80270. * @returns The quaternion rotation
  80271. */
  80272. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80274. if (mesh === void 0) { mesh = null; }
  80275. var result = BABYLON.Quaternion.Identity();
  80276. this.getRotationQuaternionToRef(space, mesh, result);
  80277. return result;
  80278. };
  80279. /**
  80280. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80281. * @param space The space that the rotation should be in
  80282. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80283. * @param result The quaternion that the rotation should be copied to
  80284. */
  80285. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80287. if (mesh === void 0) { mesh = null; }
  80288. if (space == BABYLON.Space.LOCAL) {
  80289. this._decompose();
  80290. result.copyFrom(this._localRotation);
  80291. }
  80292. else {
  80293. var mat = Bone._tmpMats[0];
  80294. var amat = this.getAbsoluteTransform();
  80295. if (mesh) {
  80296. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80297. }
  80298. else {
  80299. mat.copyFrom(amat);
  80300. }
  80301. mat.m[0] *= this._scalingDeterminant;
  80302. mat.m[1] *= this._scalingDeterminant;
  80303. mat.m[2] *= this._scalingDeterminant;
  80304. mat.decompose(undefined, result, undefined);
  80305. }
  80306. };
  80307. /**
  80308. * Get the rotation matrix of the bone in local or world space
  80309. * @param space The space that the rotation should be in
  80310. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80311. * @returns The rotation matrix
  80312. */
  80313. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80314. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80315. var result = BABYLON.Matrix.Identity();
  80316. this.getRotationMatrixToRef(space, mesh, result);
  80317. return result;
  80318. };
  80319. /**
  80320. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80321. * @param space The space that the rotation should be in
  80322. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80323. * @param result The quaternion that the rotation should be copied to
  80324. */
  80325. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80326. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80327. if (space == BABYLON.Space.LOCAL) {
  80328. this.getLocalMatrix().getRotationMatrixToRef(result);
  80329. }
  80330. else {
  80331. var mat = Bone._tmpMats[0];
  80332. var amat = this.getAbsoluteTransform();
  80333. if (mesh) {
  80334. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80335. }
  80336. else {
  80337. mat.copyFrom(amat);
  80338. }
  80339. mat.m[0] *= this._scalingDeterminant;
  80340. mat.m[1] *= this._scalingDeterminant;
  80341. mat.m[2] *= this._scalingDeterminant;
  80342. mat.getRotationMatrixToRef(result);
  80343. }
  80344. };
  80345. /**
  80346. * Get the world position of a point that is in the local space of the bone
  80347. * @param position The local position
  80348. * @param mesh The mesh that this bone is attached to
  80349. * @returns The world position
  80350. */
  80351. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80352. if (mesh === void 0) { mesh = null; }
  80353. var result = BABYLON.Vector3.Zero();
  80354. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80355. return result;
  80356. };
  80357. /**
  80358. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80359. * @param position The local position
  80360. * @param mesh The mesh that this bone is attached to
  80361. * @param result The vector3 that the world position should be copied to
  80362. */
  80363. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80364. if (mesh === void 0) { mesh = null; }
  80365. var wm = null;
  80366. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80367. if (mesh) {
  80368. wm = mesh.getWorldMatrix();
  80369. }
  80370. this._skeleton.computeAbsoluteTransforms();
  80371. var tmat = Bone._tmpMats[0];
  80372. if (mesh && wm) {
  80373. tmat.copyFrom(this.getAbsoluteTransform());
  80374. tmat.multiplyToRef(wm, tmat);
  80375. }
  80376. else {
  80377. tmat = this.getAbsoluteTransform();
  80378. }
  80379. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80380. };
  80381. /**
  80382. * Get the local position of a point that is in world space
  80383. * @param position The world position
  80384. * @param mesh The mesh that this bone is attached to
  80385. * @returns The local position
  80386. */
  80387. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80388. if (mesh === void 0) { mesh = null; }
  80389. var result = BABYLON.Vector3.Zero();
  80390. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80391. return result;
  80392. };
  80393. /**
  80394. * Get the local position of a point that is in world space and copy it to the result param
  80395. * @param position The world position
  80396. * @param mesh The mesh that this bone is attached to
  80397. * @param result The vector3 that the local position should be copied to
  80398. */
  80399. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80400. if (mesh === void 0) { mesh = null; }
  80401. var wm = null;
  80402. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80403. if (mesh) {
  80404. wm = mesh.getWorldMatrix();
  80405. }
  80406. this._skeleton.computeAbsoluteTransforms();
  80407. var tmat = Bone._tmpMats[0];
  80408. tmat.copyFrom(this.getAbsoluteTransform());
  80409. if (mesh && wm) {
  80410. tmat.multiplyToRef(wm, tmat);
  80411. }
  80412. tmat.invert();
  80413. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80414. };
  80415. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80416. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80417. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80418. return Bone;
  80419. }(BABYLON.Node));
  80420. BABYLON.Bone = Bone;
  80421. })(BABYLON || (BABYLON = {}));
  80422. //# sourceMappingURL=babylon.bone.js.map
  80423. var BABYLON;
  80424. (function (BABYLON) {
  80425. /**
  80426. * Class used to apply inverse kinematics to bones
  80427. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80428. */
  80429. var BoneIKController = /** @class */ (function () {
  80430. /**
  80431. * Creates a new BoneIKController
  80432. * @param mesh defines the mesh to control
  80433. * @param bone defines the bone to control
  80434. * @param options defines options to set up the controller
  80435. */
  80436. function BoneIKController(mesh, bone, options) {
  80437. /**
  80438. * Gets or sets the target position
  80439. */
  80440. this.targetPosition = BABYLON.Vector3.Zero();
  80441. /**
  80442. * Gets or sets the pole target position
  80443. */
  80444. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80445. /**
  80446. * Gets or sets the pole target local offset
  80447. */
  80448. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80449. /**
  80450. * Gets or sets the pole angle
  80451. */
  80452. this.poleAngle = 0;
  80453. /**
  80454. * 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)
  80455. */
  80456. this.slerpAmount = 1;
  80457. this._bone1Quat = BABYLON.Quaternion.Identity();
  80458. this._bone1Mat = BABYLON.Matrix.Identity();
  80459. this._bone2Ang = Math.PI;
  80460. this._maxAngle = Math.PI;
  80461. this._rightHandedSystem = false;
  80462. this._bendAxis = BABYLON.Vector3.Right();
  80463. this._slerping = false;
  80464. this._adjustRoll = 0;
  80465. this._bone2 = bone;
  80466. this._bone1 = bone.getParent();
  80467. if (!this._bone1) {
  80468. return;
  80469. }
  80470. this.mesh = mesh;
  80471. var bonePos = bone.getPosition();
  80472. if (bone.getAbsoluteTransform().determinant() > 0) {
  80473. this._rightHandedSystem = true;
  80474. this._bendAxis.x = 0;
  80475. this._bendAxis.y = 0;
  80476. this._bendAxis.z = -1;
  80477. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80478. this._adjustRoll = Math.PI * .5;
  80479. this._bendAxis.z = 1;
  80480. }
  80481. }
  80482. if (this._bone1.length) {
  80483. var boneScale1 = this._bone1.getScale();
  80484. var boneScale2 = this._bone2.getScale();
  80485. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80486. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80487. }
  80488. else if (this._bone1.children[0]) {
  80489. mesh.computeWorldMatrix(true);
  80490. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80491. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80492. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80493. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80494. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80495. }
  80496. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80497. this.maxAngle = Math.PI;
  80498. if (options) {
  80499. if (options.targetMesh) {
  80500. this.targetMesh = options.targetMesh;
  80501. this.targetMesh.computeWorldMatrix(true);
  80502. }
  80503. if (options.poleTargetMesh) {
  80504. this.poleTargetMesh = options.poleTargetMesh;
  80505. this.poleTargetMesh.computeWorldMatrix(true);
  80506. }
  80507. else if (options.poleTargetBone) {
  80508. this.poleTargetBone = options.poleTargetBone;
  80509. }
  80510. else if (this._bone1.getParent()) {
  80511. this.poleTargetBone = this._bone1.getParent();
  80512. }
  80513. if (options.poleTargetLocalOffset) {
  80514. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80515. }
  80516. if (options.poleAngle) {
  80517. this.poleAngle = options.poleAngle;
  80518. }
  80519. if (options.bendAxis) {
  80520. this._bendAxis.copyFrom(options.bendAxis);
  80521. }
  80522. if (options.maxAngle) {
  80523. this.maxAngle = options.maxAngle;
  80524. }
  80525. if (options.slerpAmount) {
  80526. this.slerpAmount = options.slerpAmount;
  80527. }
  80528. }
  80529. }
  80530. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80531. /**
  80532. * Gets or sets maximum allowed angle
  80533. */
  80534. get: function () {
  80535. return this._maxAngle;
  80536. },
  80537. set: function (value) {
  80538. this._setMaxAngle(value);
  80539. },
  80540. enumerable: true,
  80541. configurable: true
  80542. });
  80543. BoneIKController.prototype._setMaxAngle = function (ang) {
  80544. if (ang < 0) {
  80545. ang = 0;
  80546. }
  80547. if (ang > Math.PI || ang == undefined) {
  80548. ang = Math.PI;
  80549. }
  80550. this._maxAngle = ang;
  80551. var a = this._bone1Length;
  80552. var b = this._bone2Length;
  80553. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80554. };
  80555. /**
  80556. * Force the controller to update the bones
  80557. */
  80558. BoneIKController.prototype.update = function () {
  80559. var bone1 = this._bone1;
  80560. if (!bone1) {
  80561. return;
  80562. }
  80563. var target = this.targetPosition;
  80564. var poleTarget = this.poleTargetPosition;
  80565. var mat1 = BoneIKController._tmpMats[0];
  80566. var mat2 = BoneIKController._tmpMats[1];
  80567. if (this.targetMesh) {
  80568. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80569. }
  80570. if (this.poleTargetBone) {
  80571. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80572. }
  80573. else if (this.poleTargetMesh) {
  80574. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80575. }
  80576. var bonePos = BoneIKController._tmpVecs[0];
  80577. var zaxis = BoneIKController._tmpVecs[1];
  80578. var xaxis = BoneIKController._tmpVecs[2];
  80579. var yaxis = BoneIKController._tmpVecs[3];
  80580. var upAxis = BoneIKController._tmpVecs[4];
  80581. var _tmpQuat = BoneIKController._tmpQuat;
  80582. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80583. poleTarget.subtractToRef(bonePos, upAxis);
  80584. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80585. upAxis.y = 1;
  80586. }
  80587. else {
  80588. upAxis.normalize();
  80589. }
  80590. target.subtractToRef(bonePos, yaxis);
  80591. yaxis.normalize();
  80592. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80593. zaxis.normalize();
  80594. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80595. xaxis.normalize();
  80596. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80597. var a = this._bone1Length;
  80598. var b = this._bone2Length;
  80599. var c = BABYLON.Vector3.Distance(bonePos, target);
  80600. if (this._maxReach > 0) {
  80601. c = Math.min(this._maxReach, c);
  80602. }
  80603. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80604. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80605. if (acosa > 1) {
  80606. acosa = 1;
  80607. }
  80608. if (acosb > 1) {
  80609. acosb = 1;
  80610. }
  80611. if (acosa < -1) {
  80612. acosa = -1;
  80613. }
  80614. if (acosb < -1) {
  80615. acosb = -1;
  80616. }
  80617. var angA = Math.acos(acosa);
  80618. var angB = Math.acos(acosb);
  80619. var angC = -angA - angB;
  80620. if (this._rightHandedSystem) {
  80621. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80622. mat2.multiplyToRef(mat1, mat1);
  80623. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80624. mat2.multiplyToRef(mat1, mat1);
  80625. }
  80626. else {
  80627. var _tmpVec = BoneIKController._tmpVecs[5];
  80628. _tmpVec.copyFrom(this._bendAxis);
  80629. _tmpVec.x *= -1;
  80630. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80631. mat2.multiplyToRef(mat1, mat1);
  80632. }
  80633. if (this.poleAngle) {
  80634. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80635. mat1.multiplyToRef(mat2, mat1);
  80636. }
  80637. if (this._bone1) {
  80638. if (this.slerpAmount < 1) {
  80639. if (!this._slerping) {
  80640. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80641. }
  80642. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80643. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80644. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80645. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80646. this._slerping = true;
  80647. }
  80648. else {
  80649. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80650. this._bone1Mat.copyFrom(mat1);
  80651. this._slerping = false;
  80652. }
  80653. }
  80654. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80655. this._bone2Ang = angC;
  80656. };
  80657. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80658. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80659. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80660. return BoneIKController;
  80661. }());
  80662. BABYLON.BoneIKController = BoneIKController;
  80663. })(BABYLON || (BABYLON = {}));
  80664. //# sourceMappingURL=babylon.boneIKController.js.map
  80665. var BABYLON;
  80666. (function (BABYLON) {
  80667. /**
  80668. * Class used to make a bone look toward a point in space
  80669. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80670. */
  80671. var BoneLookController = /** @class */ (function () {
  80672. /**
  80673. * Create a BoneLookController
  80674. * @param mesh the mesh that the bone belongs to
  80675. * @param bone the bone that will be looking to the target
  80676. * @param target the target Vector3 to look at
  80677. * @param settings optional settings:
  80678. * * maxYaw: the maximum angle the bone will yaw to
  80679. * * minYaw: the minimum angle the bone will yaw to
  80680. * * maxPitch: the maximum angle the bone will pitch to
  80681. * * minPitch: the minimum angle the bone will yaw to
  80682. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80683. * * upAxis: the up axis of the coordinate system
  80684. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80685. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80686. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80687. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80688. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80689. * * adjustRoll: used to make an adjustment to the roll of the bone
  80690. **/
  80691. function BoneLookController(mesh, bone, target, options) {
  80692. /**
  80693. * The up axis of the coordinate system that is used when the bone is rotated
  80694. */
  80695. this.upAxis = BABYLON.Vector3.Up();
  80696. /**
  80697. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80698. */
  80699. this.upAxisSpace = BABYLON.Space.LOCAL;
  80700. /**
  80701. * Used to make an adjustment to the yaw of the bone
  80702. */
  80703. this.adjustYaw = 0;
  80704. /**
  80705. * Used to make an adjustment to the pitch of the bone
  80706. */
  80707. this.adjustPitch = 0;
  80708. /**
  80709. * Used to make an adjustment to the roll of the bone
  80710. */
  80711. this.adjustRoll = 0;
  80712. /**
  80713. * 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)
  80714. */
  80715. this.slerpAmount = 1;
  80716. this._boneQuat = BABYLON.Quaternion.Identity();
  80717. this._slerping = false;
  80718. this._firstFrameSkipped = false;
  80719. this._fowardAxis = BABYLON.Vector3.Forward();
  80720. this.mesh = mesh;
  80721. this.bone = bone;
  80722. this.target = target;
  80723. if (options) {
  80724. if (options.adjustYaw) {
  80725. this.adjustYaw = options.adjustYaw;
  80726. }
  80727. if (options.adjustPitch) {
  80728. this.adjustPitch = options.adjustPitch;
  80729. }
  80730. if (options.adjustRoll) {
  80731. this.adjustRoll = options.adjustRoll;
  80732. }
  80733. if (options.maxYaw != null) {
  80734. this.maxYaw = options.maxYaw;
  80735. }
  80736. else {
  80737. this.maxYaw = Math.PI;
  80738. }
  80739. if (options.minYaw != null) {
  80740. this.minYaw = options.minYaw;
  80741. }
  80742. else {
  80743. this.minYaw = -Math.PI;
  80744. }
  80745. if (options.maxPitch != null) {
  80746. this.maxPitch = options.maxPitch;
  80747. }
  80748. else {
  80749. this.maxPitch = Math.PI;
  80750. }
  80751. if (options.minPitch != null) {
  80752. this.minPitch = options.minPitch;
  80753. }
  80754. else {
  80755. this.minPitch = -Math.PI;
  80756. }
  80757. if (options.slerpAmount != null) {
  80758. this.slerpAmount = options.slerpAmount;
  80759. }
  80760. if (options.upAxis != null) {
  80761. this.upAxis = options.upAxis;
  80762. }
  80763. if (options.upAxisSpace != null) {
  80764. this.upAxisSpace = options.upAxisSpace;
  80765. }
  80766. if (options.yawAxis != null || options.pitchAxis != null) {
  80767. var newYawAxis = BABYLON.Axis.Y;
  80768. var newPitchAxis = BABYLON.Axis.X;
  80769. if (options.yawAxis != null) {
  80770. newYawAxis = options.yawAxis.clone();
  80771. newYawAxis.normalize();
  80772. }
  80773. if (options.pitchAxis != null) {
  80774. newPitchAxis = options.pitchAxis.clone();
  80775. newPitchAxis.normalize();
  80776. }
  80777. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80778. this._transformYawPitch = BABYLON.Matrix.Identity();
  80779. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80780. this._transformYawPitchInv = this._transformYawPitch.clone();
  80781. this._transformYawPitch.invert();
  80782. }
  80783. }
  80784. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80785. this.upAxisSpace = BABYLON.Space.LOCAL;
  80786. }
  80787. }
  80788. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80789. /**
  80790. * Gets or sets the minimum yaw angle that the bone can look to
  80791. */
  80792. get: function () {
  80793. return this._minYaw;
  80794. },
  80795. set: function (value) {
  80796. this._minYaw = value;
  80797. this._minYawSin = Math.sin(value);
  80798. this._minYawCos = Math.cos(value);
  80799. if (this._maxYaw != null) {
  80800. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80801. this._yawRange = this._maxYaw - this._minYaw;
  80802. }
  80803. },
  80804. enumerable: true,
  80805. configurable: true
  80806. });
  80807. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80808. /**
  80809. * Gets or sets the maximum yaw angle that the bone can look to
  80810. */
  80811. get: function () {
  80812. return this._maxYaw;
  80813. },
  80814. set: function (value) {
  80815. this._maxYaw = value;
  80816. this._maxYawSin = Math.sin(value);
  80817. this._maxYawCos = Math.cos(value);
  80818. if (this._minYaw != null) {
  80819. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80820. this._yawRange = this._maxYaw - this._minYaw;
  80821. }
  80822. },
  80823. enumerable: true,
  80824. configurable: true
  80825. });
  80826. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80827. /**
  80828. * Gets or sets the minimum pitch angle that the bone can look to
  80829. */
  80830. get: function () {
  80831. return this._minPitch;
  80832. },
  80833. set: function (value) {
  80834. this._minPitch = value;
  80835. this._minPitchTan = Math.tan(value);
  80836. },
  80837. enumerable: true,
  80838. configurable: true
  80839. });
  80840. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80841. /**
  80842. * Gets or sets the maximum pitch angle that the bone can look to
  80843. */
  80844. get: function () {
  80845. return this._maxPitch;
  80846. },
  80847. set: function (value) {
  80848. this._maxPitch = value;
  80849. this._maxPitchTan = Math.tan(value);
  80850. },
  80851. enumerable: true,
  80852. configurable: true
  80853. });
  80854. /**
  80855. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80856. */
  80857. BoneLookController.prototype.update = function () {
  80858. //skip the first frame when slerping so that the mesh rotation is correct
  80859. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80860. this._firstFrameSkipped = true;
  80861. return;
  80862. }
  80863. var bone = this.bone;
  80864. var bonePos = BoneLookController._tmpVecs[0];
  80865. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80866. var target = this.target;
  80867. var _tmpMat1 = BoneLookController._tmpMats[0];
  80868. var _tmpMat2 = BoneLookController._tmpMats[1];
  80869. var mesh = this.mesh;
  80870. var parentBone = bone.getParent();
  80871. var upAxis = BoneLookController._tmpVecs[1];
  80872. upAxis.copyFrom(this.upAxis);
  80873. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80874. if (this._transformYawPitch) {
  80875. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80876. }
  80877. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80878. }
  80879. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80880. mesh.getDirectionToRef(upAxis, upAxis);
  80881. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80882. upAxis.normalize();
  80883. }
  80884. }
  80885. var checkYaw = false;
  80886. var checkPitch = false;
  80887. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80888. checkYaw = true;
  80889. }
  80890. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80891. checkPitch = true;
  80892. }
  80893. if (checkYaw || checkPitch) {
  80894. var spaceMat = BoneLookController._tmpMats[2];
  80895. var spaceMatInv = BoneLookController._tmpMats[3];
  80896. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80897. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80898. }
  80899. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80900. spaceMat.copyFrom(mesh.getWorldMatrix());
  80901. }
  80902. else {
  80903. var forwardAxis = BoneLookController._tmpVecs[2];
  80904. forwardAxis.copyFrom(this._fowardAxis);
  80905. if (this._transformYawPitch) {
  80906. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80907. }
  80908. if (parentBone) {
  80909. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80910. }
  80911. else {
  80912. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80913. }
  80914. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80915. rightAxis.normalize();
  80916. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80917. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80918. }
  80919. spaceMat.invertToRef(spaceMatInv);
  80920. var xzlen = null;
  80921. if (checkPitch) {
  80922. var localTarget = BoneLookController._tmpVecs[3];
  80923. target.subtractToRef(bonePos, localTarget);
  80924. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80925. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80926. var pitch = Math.atan2(localTarget.y, xzlen);
  80927. var newPitch = pitch;
  80928. if (pitch > this._maxPitch) {
  80929. localTarget.y = this._maxPitchTan * xzlen;
  80930. newPitch = this._maxPitch;
  80931. }
  80932. else if (pitch < this._minPitch) {
  80933. localTarget.y = this._minPitchTan * xzlen;
  80934. newPitch = this._minPitch;
  80935. }
  80936. if (pitch != newPitch) {
  80937. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80938. localTarget.addInPlace(bonePos);
  80939. target = localTarget;
  80940. }
  80941. }
  80942. if (checkYaw) {
  80943. var localTarget = BoneLookController._tmpVecs[4];
  80944. target.subtractToRef(bonePos, localTarget);
  80945. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80946. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80947. var newYaw = yaw;
  80948. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80949. if (xzlen == null) {
  80950. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80951. }
  80952. if (this._yawRange > Math.PI) {
  80953. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80954. localTarget.z = this._maxYawCos * xzlen;
  80955. localTarget.x = this._maxYawSin * xzlen;
  80956. newYaw = this._maxYaw;
  80957. }
  80958. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80959. localTarget.z = this._minYawCos * xzlen;
  80960. localTarget.x = this._minYawSin * xzlen;
  80961. newYaw = this._minYaw;
  80962. }
  80963. }
  80964. else {
  80965. if (yaw > this._maxYaw) {
  80966. localTarget.z = this._maxYawCos * xzlen;
  80967. localTarget.x = this._maxYawSin * xzlen;
  80968. newYaw = this._maxYaw;
  80969. }
  80970. else if (yaw < this._minYaw) {
  80971. localTarget.z = this._minYawCos * xzlen;
  80972. localTarget.x = this._minYawSin * xzlen;
  80973. newYaw = this._minYaw;
  80974. }
  80975. }
  80976. }
  80977. if (this._slerping && this._yawRange > Math.PI) {
  80978. //are we going to be crossing into the min/max region?
  80979. var boneFwd = BoneLookController._tmpVecs[8];
  80980. boneFwd.copyFrom(BABYLON.Axis.Z);
  80981. if (this._transformYawPitch) {
  80982. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80983. }
  80984. var boneRotMat = BoneLookController._tmpMats[4];
  80985. this._boneQuat.toRotationMatrix(boneRotMat);
  80986. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80987. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80988. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80989. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80990. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80991. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80992. if (angBtwTar > angBtwMidYaw) {
  80993. if (xzlen == null) {
  80994. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80995. }
  80996. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80997. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80998. if (angBtwMin < angBtwMax) {
  80999. newYaw = boneYaw + Math.PI * .75;
  81000. localTarget.z = Math.cos(newYaw) * xzlen;
  81001. localTarget.x = Math.sin(newYaw) * xzlen;
  81002. }
  81003. else {
  81004. newYaw = boneYaw - Math.PI * .75;
  81005. localTarget.z = Math.cos(newYaw) * xzlen;
  81006. localTarget.x = Math.sin(newYaw) * xzlen;
  81007. }
  81008. }
  81009. }
  81010. if (yaw != newYaw) {
  81011. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81012. localTarget.addInPlace(bonePos);
  81013. target = localTarget;
  81014. }
  81015. }
  81016. }
  81017. var zaxis = BoneLookController._tmpVecs[5];
  81018. var xaxis = BoneLookController._tmpVecs[6];
  81019. var yaxis = BoneLookController._tmpVecs[7];
  81020. var _tmpQuat = BoneLookController._tmpQuat;
  81021. target.subtractToRef(bonePos, zaxis);
  81022. zaxis.normalize();
  81023. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81024. xaxis.normalize();
  81025. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81026. yaxis.normalize();
  81027. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81028. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81029. return;
  81030. }
  81031. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81032. return;
  81033. }
  81034. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81035. return;
  81036. }
  81037. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81038. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81039. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81040. }
  81041. if (this.slerpAmount < 1) {
  81042. if (!this._slerping) {
  81043. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81044. }
  81045. if (this._transformYawPitch) {
  81046. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81047. }
  81048. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81049. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81050. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81051. this._slerping = true;
  81052. }
  81053. else {
  81054. if (this._transformYawPitch) {
  81055. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81056. }
  81057. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81058. this._slerping = false;
  81059. }
  81060. };
  81061. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81062. var angDiff = ang2 - ang1;
  81063. angDiff %= Math.PI * 2;
  81064. if (angDiff > Math.PI) {
  81065. angDiff -= Math.PI * 2;
  81066. }
  81067. else if (angDiff < -Math.PI) {
  81068. angDiff += Math.PI * 2;
  81069. }
  81070. return angDiff;
  81071. };
  81072. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81073. ang1 %= (2 * Math.PI);
  81074. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81075. ang2 %= (2 * Math.PI);
  81076. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81077. var ab = 0;
  81078. if (ang1 < ang2) {
  81079. ab = ang2 - ang1;
  81080. }
  81081. else {
  81082. ab = ang1 - ang2;
  81083. }
  81084. if (ab > Math.PI) {
  81085. ab = Math.PI * 2 - ab;
  81086. }
  81087. return ab;
  81088. };
  81089. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81090. ang %= (2 * Math.PI);
  81091. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81092. ang1 %= (2 * Math.PI);
  81093. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81094. ang2 %= (2 * Math.PI);
  81095. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81096. if (ang1 < ang2) {
  81097. if (ang > ang1 && ang < ang2) {
  81098. return true;
  81099. }
  81100. }
  81101. else {
  81102. if (ang > ang2 && ang < ang1) {
  81103. return true;
  81104. }
  81105. }
  81106. return false;
  81107. };
  81108. 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()];
  81109. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81110. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81111. return BoneLookController;
  81112. }());
  81113. BABYLON.BoneLookController = BoneLookController;
  81114. })(BABYLON || (BABYLON = {}));
  81115. //# sourceMappingURL=babylon.boneLookController.js.map
  81116. var BABYLON;
  81117. (function (BABYLON) {
  81118. /**
  81119. * Class used to handle skinning animations
  81120. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81121. */
  81122. var Skeleton = /** @class */ (function () {
  81123. /**
  81124. * Creates a new skeleton
  81125. * @param name defines the skeleton name
  81126. * @param id defines the skeleton Id
  81127. * @param scene defines the hosting scene
  81128. */
  81129. function Skeleton(
  81130. /** defines the skeleton name */
  81131. name,
  81132. /** defines the skeleton Id */
  81133. id, scene) {
  81134. this.name = name;
  81135. this.id = id;
  81136. /**
  81137. * Gets the list of child bones
  81138. */
  81139. this.bones = new Array();
  81140. /**
  81141. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81142. */
  81143. this.needInitialSkinMatrix = false;
  81144. this._isDirty = true;
  81145. this._meshesWithPoseMatrix = new Array();
  81146. this._identity = BABYLON.Matrix.Identity();
  81147. this._ranges = {};
  81148. this._lastAbsoluteTransformsUpdateId = -1;
  81149. /**
  81150. * Specifies if the skeleton should be serialized
  81151. */
  81152. this.doNotSerialize = false;
  81153. this._animationPropertiesOverride = null;
  81154. // Events
  81155. /**
  81156. * An observable triggered before computing the skeleton's matrices
  81157. */
  81158. this.onBeforeComputeObservable = new BABYLON.Observable();
  81159. this.bones = [];
  81160. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81161. scene.skeletons.push(this);
  81162. //make sure it will recalculate the matrix next time prepare is called.
  81163. this._isDirty = true;
  81164. }
  81165. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81166. /**
  81167. * Gets or sets the animation properties override
  81168. */
  81169. get: function () {
  81170. if (!this._animationPropertiesOverride) {
  81171. return this._scene.animationPropertiesOverride;
  81172. }
  81173. return this._animationPropertiesOverride;
  81174. },
  81175. set: function (value) {
  81176. this._animationPropertiesOverride = value;
  81177. },
  81178. enumerable: true,
  81179. configurable: true
  81180. });
  81181. // Members
  81182. /**
  81183. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81184. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81185. * @returns a Float32Array containing matrices data
  81186. */
  81187. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81188. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81189. return mesh._bonesTransformMatrices;
  81190. }
  81191. if (!this._transformMatrices) {
  81192. this.prepare();
  81193. }
  81194. return this._transformMatrices;
  81195. };
  81196. /**
  81197. * Gets the current hosting scene
  81198. * @returns a scene object
  81199. */
  81200. Skeleton.prototype.getScene = function () {
  81201. return this._scene;
  81202. };
  81203. // Methods
  81204. /**
  81205. * Gets a string representing the current skeleton data
  81206. * @param fullDetails defines a boolean indicating if we want a verbose version
  81207. * @returns a string representing the current skeleton data
  81208. */
  81209. Skeleton.prototype.toString = function (fullDetails) {
  81210. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81211. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81212. if (fullDetails) {
  81213. ret += ", Ranges: {";
  81214. var first = true;
  81215. for (var name_1 in this._ranges) {
  81216. if (first) {
  81217. ret += ", ";
  81218. first = false;
  81219. }
  81220. ret += name_1;
  81221. }
  81222. ret += "}";
  81223. }
  81224. return ret;
  81225. };
  81226. /**
  81227. * Get bone's index searching by name
  81228. * @param name defines bone's name to search for
  81229. * @return the indice of the bone. Returns -1 if not found
  81230. */
  81231. Skeleton.prototype.getBoneIndexByName = function (name) {
  81232. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81233. if (this.bones[boneIndex].name === name) {
  81234. return boneIndex;
  81235. }
  81236. }
  81237. return -1;
  81238. };
  81239. /**
  81240. * Creater a new animation range
  81241. * @param name defines the name of the range
  81242. * @param from defines the start key
  81243. * @param to defines the end key
  81244. */
  81245. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81246. // check name not already in use
  81247. if (!this._ranges[name]) {
  81248. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81249. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81250. if (this.bones[i].animations[0]) {
  81251. this.bones[i].animations[0].createRange(name, from, to);
  81252. }
  81253. }
  81254. }
  81255. };
  81256. /**
  81257. * Delete a specific animation range
  81258. * @param name defines the name of the range
  81259. * @param deleteFrames defines if frames must be removed as well
  81260. */
  81261. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81262. if (deleteFrames === void 0) { deleteFrames = true; }
  81263. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81264. if (this.bones[i].animations[0]) {
  81265. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81266. }
  81267. }
  81268. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81269. };
  81270. /**
  81271. * Gets a specific animation range
  81272. * @param name defines the name of the range to look for
  81273. * @returns the requested animation range or null if not found
  81274. */
  81275. Skeleton.prototype.getAnimationRange = function (name) {
  81276. return this._ranges[name];
  81277. };
  81278. /**
  81279. * Gets the list of all animation ranges defined on this skeleton
  81280. * @returns an array
  81281. */
  81282. Skeleton.prototype.getAnimationRanges = function () {
  81283. var animationRanges = [];
  81284. var name;
  81285. var i = 0;
  81286. for (name in this._ranges) {
  81287. animationRanges[i] = this._ranges[name];
  81288. i++;
  81289. }
  81290. return animationRanges;
  81291. };
  81292. /**
  81293. * Copy animation range from a source skeleton.
  81294. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81295. * @param source defines the source skeleton
  81296. * @param name defines the name of the range to copy
  81297. * @param rescaleAsRequired defines if rescaling must be applied if required
  81298. * @returns true if operation was successful
  81299. */
  81300. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81301. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81302. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81303. return false;
  81304. }
  81305. var ret = true;
  81306. var frameOffset = this._getHighestAnimationFrame() + 1;
  81307. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81308. var boneDict = {};
  81309. var sourceBones = source.bones;
  81310. var nBones;
  81311. var i;
  81312. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81313. boneDict[sourceBones[i].name] = sourceBones[i];
  81314. }
  81315. if (this.bones.length !== sourceBones.length) {
  81316. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81317. ret = false;
  81318. }
  81319. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81320. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81321. var boneName = this.bones[i].name;
  81322. var sourceBone = boneDict[boneName];
  81323. if (sourceBone) {
  81324. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81325. }
  81326. else {
  81327. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81328. ret = false;
  81329. }
  81330. }
  81331. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81332. var range = source.getAnimationRange(name);
  81333. if (range) {
  81334. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81335. }
  81336. return ret;
  81337. };
  81338. /**
  81339. * Forces the skeleton to go to rest pose
  81340. */
  81341. Skeleton.prototype.returnToRest = function () {
  81342. for (var index = 0; index < this.bones.length; index++) {
  81343. this.bones[index].returnToRest();
  81344. }
  81345. };
  81346. Skeleton.prototype._getHighestAnimationFrame = function () {
  81347. var ret = 0;
  81348. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81349. if (this.bones[i].animations[0]) {
  81350. var highest = this.bones[i].animations[0].getHighestFrame();
  81351. if (ret < highest) {
  81352. ret = highest;
  81353. }
  81354. }
  81355. }
  81356. return ret;
  81357. };
  81358. /**
  81359. * Begin a specific animation range
  81360. * @param name defines the name of the range to start
  81361. * @param loop defines if looping must be turned on (false by default)
  81362. * @param speedRatio defines the speed ratio to apply (1 by default)
  81363. * @param onAnimationEnd defines a callback which will be called when animation will end
  81364. * @returns a new animatable
  81365. */
  81366. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81367. var range = this.getAnimationRange(name);
  81368. if (!range) {
  81369. return null;
  81370. }
  81371. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81372. };
  81373. /** @hidden */
  81374. Skeleton.prototype._markAsDirty = function () {
  81375. this._isDirty = true;
  81376. };
  81377. /** @hidden */
  81378. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81379. this._meshesWithPoseMatrix.push(mesh);
  81380. };
  81381. /** @hidden */
  81382. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81383. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81384. if (index > -1) {
  81385. this._meshesWithPoseMatrix.splice(index, 1);
  81386. }
  81387. };
  81388. /** @hidden */
  81389. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81390. this.onBeforeComputeObservable.notifyObservers(this);
  81391. for (var index = 0; index < this.bones.length; index++) {
  81392. var bone = this.bones[index];
  81393. var parentBone = bone.getParent();
  81394. if (parentBone) {
  81395. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81396. }
  81397. else {
  81398. if (initialSkinMatrix) {
  81399. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81400. }
  81401. else {
  81402. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81403. }
  81404. }
  81405. if (bone._index !== -1) {
  81406. var mappedIndex = bone._index === null ? index : bone._index;
  81407. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81408. }
  81409. }
  81410. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81411. };
  81412. /**
  81413. * Build all resources required to render a skeleton
  81414. */
  81415. Skeleton.prototype.prepare = function () {
  81416. if (!this._isDirty) {
  81417. return;
  81418. }
  81419. if (this.needInitialSkinMatrix) {
  81420. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81421. var mesh = this._meshesWithPoseMatrix[index];
  81422. var poseMatrix = mesh.getPoseMatrix();
  81423. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81424. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81425. }
  81426. if (this._synchronizedWithMesh !== mesh) {
  81427. this._synchronizedWithMesh = mesh;
  81428. // Prepare bones
  81429. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81430. var bone = this.bones[boneIndex];
  81431. if (!bone.getParent()) {
  81432. var matrix = bone.getBaseMatrix();
  81433. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81434. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81435. }
  81436. }
  81437. }
  81438. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81439. }
  81440. }
  81441. else {
  81442. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81443. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81444. }
  81445. this._computeTransformMatrices(this._transformMatrices, null);
  81446. }
  81447. this._isDirty = false;
  81448. this._scene._activeBones.addCount(this.bones.length, false);
  81449. };
  81450. /**
  81451. * Gets the list of animatables currently running for this skeleton
  81452. * @returns an array of animatables
  81453. */
  81454. Skeleton.prototype.getAnimatables = function () {
  81455. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81456. this._animatables = [];
  81457. for (var index = 0; index < this.bones.length; index++) {
  81458. this._animatables.push(this.bones[index]);
  81459. }
  81460. }
  81461. return this._animatables;
  81462. };
  81463. /**
  81464. * Clone the current skeleton
  81465. * @param name defines the name of the new skeleton
  81466. * @param id defines the id of the enw skeleton
  81467. * @returns the new skeleton
  81468. */
  81469. Skeleton.prototype.clone = function (name, id) {
  81470. var result = new Skeleton(name, id || name, this._scene);
  81471. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81472. for (var index = 0; index < this.bones.length; index++) {
  81473. var source = this.bones[index];
  81474. var parentBone = null;
  81475. var parent_1 = source.getParent();
  81476. if (parent_1) {
  81477. var parentIndex = this.bones.indexOf(parent_1);
  81478. parentBone = result.bones[parentIndex];
  81479. }
  81480. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81481. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81482. }
  81483. if (this._ranges) {
  81484. result._ranges = {};
  81485. for (var rangeName in this._ranges) {
  81486. var range = this._ranges[rangeName];
  81487. if (range) {
  81488. result._ranges[rangeName] = range.clone();
  81489. }
  81490. }
  81491. }
  81492. this._isDirty = true;
  81493. return result;
  81494. };
  81495. /**
  81496. * Enable animation blending for this skeleton
  81497. * @param blendingSpeed defines the blending speed to apply
  81498. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81499. */
  81500. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81501. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81502. this.bones.forEach(function (bone) {
  81503. bone.animations.forEach(function (animation) {
  81504. animation.enableBlending = true;
  81505. animation.blendingSpeed = blendingSpeed;
  81506. });
  81507. });
  81508. };
  81509. /**
  81510. * Releases all resources associated with the current skeleton
  81511. */
  81512. Skeleton.prototype.dispose = function () {
  81513. this._meshesWithPoseMatrix = [];
  81514. // Animations
  81515. this.getScene().stopAnimation(this);
  81516. // Remove from scene
  81517. this.getScene().removeSkeleton(this);
  81518. };
  81519. /**
  81520. * Serialize the skeleton in a JSON object
  81521. * @returns a JSON object
  81522. */
  81523. Skeleton.prototype.serialize = function () {
  81524. var serializationObject = {};
  81525. serializationObject.name = this.name;
  81526. serializationObject.id = this.id;
  81527. if (this.dimensionsAtRest) {
  81528. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81529. }
  81530. serializationObject.bones = [];
  81531. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81532. for (var index = 0; index < this.bones.length; index++) {
  81533. var bone = this.bones[index];
  81534. var parent_2 = bone.getParent();
  81535. var serializedBone = {
  81536. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81537. name: bone.name,
  81538. matrix: bone.getBaseMatrix().toArray(),
  81539. rest: bone.getRestPose().toArray()
  81540. };
  81541. serializationObject.bones.push(serializedBone);
  81542. if (bone.length) {
  81543. serializedBone.length = bone.length;
  81544. }
  81545. if (bone.metadata) {
  81546. serializedBone.metadata = bone.metadata;
  81547. }
  81548. if (bone.animations && bone.animations.length > 0) {
  81549. serializedBone.animation = bone.animations[0].serialize();
  81550. }
  81551. serializationObject.ranges = [];
  81552. for (var name in this._ranges) {
  81553. var source = this._ranges[name];
  81554. if (!source) {
  81555. continue;
  81556. }
  81557. var range = {};
  81558. range.name = name;
  81559. range.from = source.from;
  81560. range.to = source.to;
  81561. serializationObject.ranges.push(range);
  81562. }
  81563. }
  81564. return serializationObject;
  81565. };
  81566. /**
  81567. * Creates a new skeleton from serialized data
  81568. * @param parsedSkeleton defines the serialized data
  81569. * @param scene defines the hosting scene
  81570. * @returns a new skeleton
  81571. */
  81572. Skeleton.Parse = function (parsedSkeleton, scene) {
  81573. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81574. if (parsedSkeleton.dimensionsAtRest) {
  81575. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81576. }
  81577. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81578. var index;
  81579. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81580. var parsedBone = parsedSkeleton.bones[index];
  81581. var parentBone = null;
  81582. if (parsedBone.parentBoneIndex > -1) {
  81583. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81584. }
  81585. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81586. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81587. if (parsedBone.length) {
  81588. bone.length = parsedBone.length;
  81589. }
  81590. if (parsedBone.metadata) {
  81591. bone.metadata = parsedBone.metadata;
  81592. }
  81593. if (parsedBone.animation) {
  81594. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81595. }
  81596. }
  81597. // placed after bones, so createAnimationRange can cascade down
  81598. if (parsedSkeleton.ranges) {
  81599. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81600. var data = parsedSkeleton.ranges[index];
  81601. skeleton.createAnimationRange(data.name, data.from, data.to);
  81602. }
  81603. }
  81604. return skeleton;
  81605. };
  81606. /**
  81607. * Compute all node absolute transforms
  81608. * @param forceUpdate defines if computation must be done even if cache is up to date
  81609. */
  81610. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81611. if (forceUpdate === void 0) { forceUpdate = false; }
  81612. var renderId = this._scene.getRenderId();
  81613. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81614. this.bones[0].computeAbsoluteTransforms();
  81615. this._lastAbsoluteTransformsUpdateId = renderId;
  81616. }
  81617. };
  81618. /**
  81619. * Gets the root pose matrix
  81620. * @returns a matrix
  81621. */
  81622. Skeleton.prototype.getPoseMatrix = function () {
  81623. var poseMatrix = null;
  81624. if (this._meshesWithPoseMatrix.length > 0) {
  81625. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81626. }
  81627. return poseMatrix;
  81628. };
  81629. /**
  81630. * Sorts bones per internal index
  81631. */
  81632. Skeleton.prototype.sortBones = function () {
  81633. var bones = new Array();
  81634. var visited = new Array(this.bones.length);
  81635. for (var index = 0; index < this.bones.length; index++) {
  81636. this._sortBones(index, bones, visited);
  81637. }
  81638. this.bones = bones;
  81639. };
  81640. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81641. if (visited[index]) {
  81642. return;
  81643. }
  81644. visited[index] = true;
  81645. var bone = this.bones[index];
  81646. if (bone._index === undefined) {
  81647. bone._index = index;
  81648. }
  81649. var parentBone = bone.getParent();
  81650. if (parentBone) {
  81651. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81652. }
  81653. bones.push(bone);
  81654. };
  81655. return Skeleton;
  81656. }());
  81657. BABYLON.Skeleton = Skeleton;
  81658. })(BABYLON || (BABYLON = {}));
  81659. //# sourceMappingURL=babylon.skeleton.js.map
  81660. var BABYLON;
  81661. (function (BABYLON) {
  81662. /**
  81663. * Class representing spherical polynomial coefficients to the 3rd degree
  81664. */
  81665. var SphericalPolynomial = /** @class */ (function () {
  81666. function SphericalPolynomial() {
  81667. /**
  81668. * The x coefficients of the spherical polynomial
  81669. */
  81670. this.x = BABYLON.Vector3.Zero();
  81671. /**
  81672. * The y coefficients of the spherical polynomial
  81673. */
  81674. this.y = BABYLON.Vector3.Zero();
  81675. /**
  81676. * The z coefficients of the spherical polynomial
  81677. */
  81678. this.z = BABYLON.Vector3.Zero();
  81679. /**
  81680. * The xx coefficients of the spherical polynomial
  81681. */
  81682. this.xx = BABYLON.Vector3.Zero();
  81683. /**
  81684. * The yy coefficients of the spherical polynomial
  81685. */
  81686. this.yy = BABYLON.Vector3.Zero();
  81687. /**
  81688. * The zz coefficients of the spherical polynomial
  81689. */
  81690. this.zz = BABYLON.Vector3.Zero();
  81691. /**
  81692. * The xy coefficients of the spherical polynomial
  81693. */
  81694. this.xy = BABYLON.Vector3.Zero();
  81695. /**
  81696. * The yz coefficients of the spherical polynomial
  81697. */
  81698. this.yz = BABYLON.Vector3.Zero();
  81699. /**
  81700. * The zx coefficients of the spherical polynomial
  81701. */
  81702. this.zx = BABYLON.Vector3.Zero();
  81703. }
  81704. /**
  81705. * Adds an ambient color to the spherical polynomial
  81706. * @param color the color to add
  81707. */
  81708. SphericalPolynomial.prototype.addAmbient = function (color) {
  81709. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81710. this.xx = this.xx.add(colorVector);
  81711. this.yy = this.yy.add(colorVector);
  81712. this.zz = this.zz.add(colorVector);
  81713. };
  81714. /**
  81715. * Scales the spherical polynomial by the given amount
  81716. * @param scale the amount to scale
  81717. */
  81718. SphericalPolynomial.prototype.scale = function (scale) {
  81719. this.x = this.x.scale(scale);
  81720. this.y = this.y.scale(scale);
  81721. this.z = this.z.scale(scale);
  81722. this.xx = this.xx.scale(scale);
  81723. this.yy = this.yy.scale(scale);
  81724. this.zz = this.zz.scale(scale);
  81725. this.yz = this.yz.scale(scale);
  81726. this.zx = this.zx.scale(scale);
  81727. this.xy = this.xy.scale(scale);
  81728. };
  81729. /**
  81730. * Gets the spherical polynomial from harmonics
  81731. * @param harmonics the spherical harmonics
  81732. * @returns the spherical polynomial
  81733. */
  81734. SphericalPolynomial.FromHarmonics = function (harmonics) {
  81735. var result = new SphericalPolynomial();
  81736. result.x = harmonics.l11.scale(1.02333);
  81737. result.y = harmonics.l1_1.scale(1.02333);
  81738. result.z = harmonics.l10.scale(1.02333);
  81739. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  81740. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  81741. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  81742. result.yz = harmonics.l2_1.scale(0.858086);
  81743. result.zx = harmonics.l21.scale(0.858086);
  81744. result.xy = harmonics.l2_2.scale(0.858086);
  81745. result.scale(1.0 / Math.PI);
  81746. return result;
  81747. };
  81748. /**
  81749. * Constructs a spherical polynomial from an array.
  81750. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  81751. * @returns the spherical polynomial
  81752. */
  81753. SphericalPolynomial.FromArray = function (data) {
  81754. var sp = new SphericalPolynomial();
  81755. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  81756. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  81757. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  81758. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  81759. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  81760. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  81761. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  81762. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  81763. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  81764. return sp;
  81765. };
  81766. return SphericalPolynomial;
  81767. }());
  81768. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81769. /**
  81770. * Class representing spherical harmonics coefficients to the 3rd degree
  81771. */
  81772. var SphericalHarmonics = /** @class */ (function () {
  81773. function SphericalHarmonics() {
  81774. /**
  81775. * The l0,0 coefficients of the spherical harmonics
  81776. */
  81777. this.l00 = BABYLON.Vector3.Zero();
  81778. /**
  81779. * The l1,-1 coefficients of the spherical harmonics
  81780. */
  81781. this.l1_1 = BABYLON.Vector3.Zero();
  81782. /**
  81783. * The l1,0 coefficients of the spherical harmonics
  81784. */
  81785. this.l10 = BABYLON.Vector3.Zero();
  81786. /**
  81787. * The l1,1 coefficients of the spherical harmonics
  81788. */
  81789. this.l11 = BABYLON.Vector3.Zero();
  81790. /**
  81791. * The l2,-2 coefficients of the spherical harmonics
  81792. */
  81793. this.l2_2 = BABYLON.Vector3.Zero();
  81794. /**
  81795. * The l2,-1 coefficients of the spherical harmonics
  81796. */
  81797. this.l2_1 = BABYLON.Vector3.Zero();
  81798. /**
  81799. * The l2,0 coefficients of the spherical harmonics
  81800. */
  81801. this.l20 = BABYLON.Vector3.Zero();
  81802. /**
  81803. * The l2,1 coefficients of the spherical harmonics
  81804. */
  81805. this.l21 = BABYLON.Vector3.Zero();
  81806. /**
  81807. * The l2,2 coefficients of the spherical harmonics
  81808. */
  81809. this.lL22 = BABYLON.Vector3.Zero();
  81810. }
  81811. /**
  81812. * Adds a light to the spherical harmonics
  81813. * @param direction the direction of the light
  81814. * @param color the color of the light
  81815. * @param deltaSolidAngle the delta solid angle of the light
  81816. */
  81817. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81818. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81819. var c = colorVector.scale(deltaSolidAngle);
  81820. this.l00 = this.l00.add(c.scale(0.282095));
  81821. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  81822. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  81823. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  81824. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81825. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81826. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  81827. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81828. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81829. };
  81830. /**
  81831. * Scales the spherical harmonics by the given amount
  81832. * @param scale the amount to scale
  81833. */
  81834. SphericalHarmonics.prototype.scale = function (scale) {
  81835. this.l00 = this.l00.scale(scale);
  81836. this.l1_1 = this.l1_1.scale(scale);
  81837. this.l10 = this.l10.scale(scale);
  81838. this.l11 = this.l11.scale(scale);
  81839. this.l2_2 = this.l2_2.scale(scale);
  81840. this.l2_1 = this.l2_1.scale(scale);
  81841. this.l20 = this.l20.scale(scale);
  81842. this.l21 = this.l21.scale(scale);
  81843. this.lL22 = this.lL22.scale(scale);
  81844. };
  81845. /**
  81846. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81847. *
  81848. * ```
  81849. * E_lm = A_l * L_lm
  81850. * ```
  81851. *
  81852. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81853. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81854. * the scaling factors are given in equation 9.
  81855. */
  81856. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81857. // Constant (Band 0)
  81858. this.l00 = this.l00.scale(3.141593);
  81859. // Linear (Band 1)
  81860. this.l1_1 = this.l1_1.scale(2.094395);
  81861. this.l10 = this.l10.scale(2.094395);
  81862. this.l11 = this.l11.scale(2.094395);
  81863. // Quadratic (Band 2)
  81864. this.l2_2 = this.l2_2.scale(0.785398);
  81865. this.l2_1 = this.l2_1.scale(0.785398);
  81866. this.l20 = this.l20.scale(0.785398);
  81867. this.l21 = this.l21.scale(0.785398);
  81868. this.lL22 = this.lL22.scale(0.785398);
  81869. };
  81870. /**
  81871. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81872. *
  81873. * ```
  81874. * L = (1/pi) * E * rho
  81875. * ```
  81876. *
  81877. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81878. */
  81879. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81880. this.scale(1.0 / Math.PI);
  81881. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81882. // (The pixel shader must apply albedo after texture fetches, etc).
  81883. };
  81884. /**
  81885. * Gets the spherical harmonics from polynomial
  81886. * @param polynomial the spherical polynomial
  81887. * @returns the spherical harmonics
  81888. */
  81889. SphericalHarmonics.FromPolynomial = function (polynomial) {
  81890. var result = new SphericalHarmonics();
  81891. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81892. result.l1_1 = polynomial.y.scale(0.977204);
  81893. result.l10 = polynomial.z.scale(0.977204);
  81894. result.l11 = polynomial.x.scale(0.977204);
  81895. result.l2_2 = polynomial.xy.scale(1.16538);
  81896. result.l2_1 = polynomial.yz.scale(1.16538);
  81897. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81898. result.l21 = polynomial.zx.scale(1.16538);
  81899. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81900. result.scale(Math.PI);
  81901. return result;
  81902. };
  81903. /**
  81904. * Constructs a spherical harmonics from an array.
  81905. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  81906. * @returns the spherical harmonics
  81907. */
  81908. SphericalHarmonics.FromArray = function (data) {
  81909. var sh = new SphericalHarmonics();
  81910. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  81911. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  81912. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  81913. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  81914. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  81915. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  81916. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  81917. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  81918. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  81919. return sh;
  81920. };
  81921. return SphericalHarmonics;
  81922. }());
  81923. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81924. })(BABYLON || (BABYLON = {}));
  81925. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81926. var BABYLON;
  81927. (function (BABYLON) {
  81928. var FileFaceOrientation = /** @class */ (function () {
  81929. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81930. this.name = name;
  81931. this.worldAxisForNormal = worldAxisForNormal;
  81932. this.worldAxisForFileX = worldAxisForFileX;
  81933. this.worldAxisForFileY = worldAxisForFileY;
  81934. }
  81935. return FileFaceOrientation;
  81936. }());
  81937. ;
  81938. /**
  81939. * Helper class dealing with the extraction of spherical polynomial dataArray
  81940. * from a cube map.
  81941. */
  81942. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81943. function CubeMapToSphericalPolynomialTools() {
  81944. }
  81945. /**
  81946. * Converts a texture to the according Spherical Polynomial data.
  81947. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81948. *
  81949. * @param texture The texture to extract the information from.
  81950. * @return The Spherical Polynomial data.
  81951. */
  81952. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81953. if (!texture.isCube) {
  81954. // Only supports cube Textures currently.
  81955. return null;
  81956. }
  81957. var size = texture.getSize().width;
  81958. var right = texture.readPixels(0);
  81959. var left = texture.readPixels(1);
  81960. var up;
  81961. var down;
  81962. if (texture.isRenderTarget) {
  81963. up = texture.readPixels(3);
  81964. down = texture.readPixels(2);
  81965. }
  81966. else {
  81967. up = texture.readPixels(2);
  81968. down = texture.readPixels(3);
  81969. }
  81970. var front = texture.readPixels(4);
  81971. var back = texture.readPixels(5);
  81972. var gammaSpace = texture.gammaSpace;
  81973. // Always read as RGBA.
  81974. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81975. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81976. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81977. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81978. }
  81979. var cubeInfo = {
  81980. size: size,
  81981. right: right,
  81982. left: left,
  81983. up: up,
  81984. down: down,
  81985. front: front,
  81986. back: back,
  81987. format: format,
  81988. type: type,
  81989. gammaSpace: gammaSpace,
  81990. };
  81991. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81992. };
  81993. /**
  81994. * Converts a cubemap to the according Spherical Polynomial data.
  81995. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81996. *
  81997. * @param cubeInfo The Cube map to extract the information from.
  81998. * @return The Spherical Polynomial data.
  81999. */
  82000. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82001. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82002. var totalSolidAngle = 0.0;
  82003. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82004. var du = 2.0 / cubeInfo.size;
  82005. var dv = du;
  82006. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82007. var minUV = du * 0.5 - 1.0;
  82008. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82009. var fileFace = this.FileFaces[faceIndex];
  82010. var dataArray = cubeInfo[fileFace.name];
  82011. var v = minUV;
  82012. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82013. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82014. // Because SP is still linear, so summation is fine in that basis.
  82015. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82016. for (var y = 0; y < cubeInfo.size; y++) {
  82017. var u = minUV;
  82018. for (var x = 0; x < cubeInfo.size; x++) {
  82019. // World direction (not normalised)
  82020. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82021. worldDirection.normalize();
  82022. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82023. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82024. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82025. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82026. // Handle Integer types.
  82027. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82028. r /= 255;
  82029. g /= 255;
  82030. b /= 255;
  82031. }
  82032. // Handle Gamma space textures.
  82033. if (cubeInfo.gammaSpace) {
  82034. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82035. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82036. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82037. }
  82038. var color = new BABYLON.Color3(r, g, b);
  82039. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82040. totalSolidAngle += deltaSolidAngle;
  82041. u += du;
  82042. }
  82043. v += dv;
  82044. }
  82045. }
  82046. // Solid angle for entire sphere is 4*pi
  82047. var sphereSolidAngle = 4.0 * Math.PI;
  82048. // Adjust the solid angle to allow for how many faces we processed.
  82049. var facesProcessed = 6.0;
  82050. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82051. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82052. // This is needed because the numerical integration over the cube uses a
  82053. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82054. // and also to compensate for accumulative error due to float precision in the summation.
  82055. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82056. sphericalHarmonics.scale(correctionFactor);
  82057. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82058. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82059. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82060. };
  82061. CubeMapToSphericalPolynomialTools.FileFaces = [
  82062. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82063. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82064. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82065. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82066. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82067. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82068. ];
  82069. return CubeMapToSphericalPolynomialTools;
  82070. }());
  82071. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82072. })(BABYLON || (BABYLON = {}));
  82073. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82074. var BABYLON;
  82075. (function (BABYLON) {
  82076. /**
  82077. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82078. */
  82079. var PanoramaToCubeMapTools = /** @class */ (function () {
  82080. function PanoramaToCubeMapTools() {
  82081. }
  82082. /**
  82083. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82084. *
  82085. * @param float32Array The source data.
  82086. * @param inputWidth The width of the input panorama.
  82087. * @param inputhHeight The height of the input panorama.
  82088. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82089. * @return The cubemap data
  82090. */
  82091. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82092. if (!float32Array) {
  82093. throw "ConvertPanoramaToCubemap: input cannot be null";
  82094. }
  82095. if (float32Array.length != inputWidth * inputHeight * 3) {
  82096. throw "ConvertPanoramaToCubemap: input size is wrong";
  82097. }
  82098. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82099. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82100. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82101. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82102. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82103. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82104. return {
  82105. front: textureFront,
  82106. back: textureBack,
  82107. left: textureLeft,
  82108. right: textureRight,
  82109. up: textureUp,
  82110. down: textureDown,
  82111. size: size,
  82112. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82113. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82114. gammaSpace: false,
  82115. };
  82116. };
  82117. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82118. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82119. var textureArray = new Float32Array(buffer);
  82120. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82121. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82122. var dy = 1 / texSize;
  82123. var fy = 0;
  82124. for (var y = 0; y < texSize; y++) {
  82125. var xv1 = faceData[0];
  82126. var xv2 = faceData[2];
  82127. for (var x = 0; x < texSize; x++) {
  82128. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82129. v.normalize();
  82130. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82131. // 3 channels per pixels
  82132. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82133. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82134. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82135. xv1 = xv1.add(rotDX1);
  82136. xv2 = xv2.add(rotDX2);
  82137. }
  82138. fy += dy;
  82139. }
  82140. return textureArray;
  82141. };
  82142. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82143. var theta = Math.atan2(vDir.z, vDir.x);
  82144. var phi = Math.acos(vDir.y);
  82145. while (theta < -Math.PI)
  82146. theta += 2 * Math.PI;
  82147. while (theta > Math.PI)
  82148. theta -= 2 * Math.PI;
  82149. var dx = theta / Math.PI;
  82150. var dy = phi / Math.PI;
  82151. // recenter.
  82152. dx = dx * 0.5 + 0.5;
  82153. var px = Math.round(dx * inputWidth);
  82154. if (px < 0)
  82155. px = 0;
  82156. else if (px >= inputWidth)
  82157. px = inputWidth - 1;
  82158. var py = Math.round(dy * inputHeight);
  82159. if (py < 0)
  82160. py = 0;
  82161. else if (py >= inputHeight)
  82162. py = inputHeight - 1;
  82163. var inputY = (inputHeight - py - 1);
  82164. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82165. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82166. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82167. return {
  82168. r: r,
  82169. g: g,
  82170. b: b
  82171. };
  82172. };
  82173. PanoramaToCubeMapTools.FACE_FRONT = [
  82174. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82175. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82176. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82177. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82178. ];
  82179. PanoramaToCubeMapTools.FACE_BACK = [
  82180. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82181. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82182. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82183. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82184. ];
  82185. PanoramaToCubeMapTools.FACE_RIGHT = [
  82186. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82187. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82188. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82189. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82190. ];
  82191. PanoramaToCubeMapTools.FACE_LEFT = [
  82192. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82193. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82194. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82195. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82196. ];
  82197. PanoramaToCubeMapTools.FACE_DOWN = [
  82198. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82199. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82200. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82201. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82202. ];
  82203. PanoramaToCubeMapTools.FACE_UP = [
  82204. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82205. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82206. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82207. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82208. ];
  82209. return PanoramaToCubeMapTools;
  82210. }());
  82211. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82212. })(BABYLON || (BABYLON = {}));
  82213. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82214. var BABYLON;
  82215. (function (BABYLON) {
  82216. ;
  82217. /**
  82218. * This groups tools to convert HDR texture to native colors array.
  82219. */
  82220. var HDRTools = /** @class */ (function () {
  82221. function HDRTools() {
  82222. }
  82223. HDRTools.Ldexp = function (mantissa, exponent) {
  82224. if (exponent > 1023) {
  82225. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82226. }
  82227. if (exponent < -1074) {
  82228. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82229. }
  82230. return mantissa * Math.pow(2, exponent);
  82231. };
  82232. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82233. if (exponent > 0) { /*nonzero pixel*/
  82234. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82235. float32array[index + 0] = red * exponent;
  82236. float32array[index + 1] = green * exponent;
  82237. float32array[index + 2] = blue * exponent;
  82238. }
  82239. else {
  82240. float32array[index + 0] = 0;
  82241. float32array[index + 1] = 0;
  82242. float32array[index + 2] = 0;
  82243. }
  82244. };
  82245. HDRTools.readStringLine = function (uint8array, startIndex) {
  82246. var line = "";
  82247. var character = "";
  82248. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82249. character = String.fromCharCode(uint8array[i]);
  82250. if (character == "\n") {
  82251. break;
  82252. }
  82253. line += character;
  82254. }
  82255. return line;
  82256. };
  82257. /**
  82258. * Reads header information from an RGBE texture stored in a native array.
  82259. * More information on this format are available here:
  82260. * https://en.wikipedia.org/wiki/RGBE_image_format
  82261. *
  82262. * @param uint8array The binary file stored in native array.
  82263. * @return The header information.
  82264. */
  82265. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82266. var height = 0;
  82267. var width = 0;
  82268. var line = this.readStringLine(uint8array, 0);
  82269. if (line[0] != '#' || line[1] != '?') {
  82270. throw "Bad HDR Format.";
  82271. }
  82272. var endOfHeader = false;
  82273. var findFormat = false;
  82274. var lineIndex = 0;
  82275. do {
  82276. lineIndex += (line.length + 1);
  82277. line = this.readStringLine(uint8array, lineIndex);
  82278. if (line == "FORMAT=32-bit_rle_rgbe") {
  82279. findFormat = true;
  82280. }
  82281. else if (line.length == 0) {
  82282. endOfHeader = true;
  82283. }
  82284. } while (!endOfHeader);
  82285. if (!findFormat) {
  82286. throw "HDR Bad header format, unsupported FORMAT";
  82287. }
  82288. lineIndex += (line.length + 1);
  82289. line = this.readStringLine(uint8array, lineIndex);
  82290. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82291. var match = sizeRegexp.exec(line);
  82292. // TODO. Support +Y and -X if needed.
  82293. if (!match || match.length < 3) {
  82294. throw "HDR Bad header format, no size";
  82295. }
  82296. width = parseInt(match[2]);
  82297. height = parseInt(match[1]);
  82298. if (width < 8 || width > 0x7fff) {
  82299. throw "HDR Bad header format, unsupported size";
  82300. }
  82301. lineIndex += (line.length + 1);
  82302. return {
  82303. height: height,
  82304. width: width,
  82305. dataPosition: lineIndex
  82306. };
  82307. };
  82308. /**
  82309. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82310. * This RGBE texture needs to store the information as a panorama.
  82311. *
  82312. * More information on this format are available here:
  82313. * https://en.wikipedia.org/wiki/RGBE_image_format
  82314. *
  82315. * @param buffer The binary file stored in an array buffer.
  82316. * @param size The expected size of the extracted cubemap.
  82317. * @return The Cube Map information.
  82318. */
  82319. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82320. var uint8array = new Uint8Array(buffer);
  82321. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82322. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82323. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82324. return cubeMapData;
  82325. };
  82326. /**
  82327. * Returns the pixels data extracted from an RGBE texture.
  82328. * This pixels will be stored left to right up to down in the R G B order in one array.
  82329. *
  82330. * More information on this format are available here:
  82331. * https://en.wikipedia.org/wiki/RGBE_image_format
  82332. *
  82333. * @param uint8array The binary file stored in an array buffer.
  82334. * @param hdrInfo The header information of the file.
  82335. * @return The pixels data in RGB right to left up to down order.
  82336. */
  82337. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82338. // Keep for multi format supports.
  82339. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82340. };
  82341. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82342. var num_scanlines = hdrInfo.height;
  82343. var scanline_width = hdrInfo.width;
  82344. var a, b, c, d, count;
  82345. var dataIndex = hdrInfo.dataPosition;
  82346. var index = 0, endIndex = 0, i = 0;
  82347. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82348. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82349. // 3 channels of 4 bytes per pixel in float.
  82350. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82351. var resultArray = new Float32Array(resultBuffer);
  82352. // read in each successive scanline
  82353. while (num_scanlines > 0) {
  82354. a = uint8array[dataIndex++];
  82355. b = uint8array[dataIndex++];
  82356. c = uint8array[dataIndex++];
  82357. d = uint8array[dataIndex++];
  82358. if (a != 2 || b != 2 || (c & 0x80)) {
  82359. // this file is not run length encoded
  82360. throw "HDR Bad header format, not RLE";
  82361. }
  82362. if (((c << 8) | d) != scanline_width) {
  82363. throw "HDR Bad header format, wrong scan line width";
  82364. }
  82365. index = 0;
  82366. // read each of the four channels for the scanline into the buffer
  82367. for (i = 0; i < 4; i++) {
  82368. endIndex = (i + 1) * scanline_width;
  82369. while (index < endIndex) {
  82370. a = uint8array[dataIndex++];
  82371. b = uint8array[dataIndex++];
  82372. if (a > 128) {
  82373. // a run of the same value
  82374. count = a - 128;
  82375. if ((count == 0) || (count > endIndex - index)) {
  82376. throw "HDR Bad Format, bad scanline data (run)";
  82377. }
  82378. while (count-- > 0) {
  82379. scanLineArray[index++] = b;
  82380. }
  82381. }
  82382. else {
  82383. // a non-run
  82384. count = a;
  82385. if ((count == 0) || (count > endIndex - index)) {
  82386. throw "HDR Bad Format, bad scanline data (non-run)";
  82387. }
  82388. scanLineArray[index++] = b;
  82389. if (--count > 0) {
  82390. for (var j = 0; j < count; j++) {
  82391. scanLineArray[index++] = uint8array[dataIndex++];
  82392. }
  82393. }
  82394. }
  82395. }
  82396. }
  82397. // now convert data from buffer into floats
  82398. for (i = 0; i < scanline_width; i++) {
  82399. a = scanLineArray[i];
  82400. b = scanLineArray[i + scanline_width];
  82401. c = scanLineArray[i + 2 * scanline_width];
  82402. d = scanLineArray[i + 3 * scanline_width];
  82403. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82404. }
  82405. num_scanlines--;
  82406. }
  82407. return resultArray;
  82408. };
  82409. return HDRTools;
  82410. }());
  82411. BABYLON.HDRTools = HDRTools;
  82412. })(BABYLON || (BABYLON = {}));
  82413. //# sourceMappingURL=babylon.hdr.js.map
  82414. var BABYLON;
  82415. (function (BABYLON) {
  82416. /**
  82417. * Sets of helpers addressing the serialization and deserialization of environment texture
  82418. * stored in a BabylonJS env file.
  82419. * Those files are usually stored as .env files.
  82420. */
  82421. var EnvironmentTextureTools = /** @class */ (function () {
  82422. function EnvironmentTextureTools() {
  82423. }
  82424. /**
  82425. * Gets the environment info from an env file.
  82426. * @param data The array buffer containing the .env bytes.
  82427. * @returns the environment file info (the json header) if successfully parsed.
  82428. */
  82429. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82430. var dataView = new DataView(data);
  82431. var pos = 0;
  82432. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82433. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82434. BABYLON.Tools.Error('Not a babylon environment map');
  82435. return null;
  82436. }
  82437. }
  82438. // Read json manifest - collect characters up to null terminator
  82439. var manifestString = '';
  82440. var charCode = 0x00;
  82441. while ((charCode = dataView.getUint8(pos++))) {
  82442. manifestString += String.fromCharCode(charCode);
  82443. }
  82444. var manifest = JSON.parse(manifestString);
  82445. if (manifest.specular) {
  82446. // Extend the header with the position of the payload.
  82447. manifest.specular.specularDataPosition = pos;
  82448. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  82449. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  82450. }
  82451. return manifest;
  82452. };
  82453. /**
  82454. * Creates an environment texture from a loaded cube texture.
  82455. * @param texture defines the cube texture to convert in env file
  82456. * @return a promise containing the environment data if succesfull.
  82457. */
  82458. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82459. var _this = this;
  82460. var internalTexture = texture.getInternalTexture();
  82461. if (!internalTexture) {
  82462. return Promise.reject("The cube texture is invalid.");
  82463. }
  82464. if (!texture._prefiltered) {
  82465. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82466. }
  82467. var engine = internalTexture.getEngine();
  82468. if (engine && engine.premultipliedAlpha) {
  82469. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82470. }
  82471. var canvas = engine.getRenderingCanvas();
  82472. if (!canvas) {
  82473. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82474. }
  82475. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82476. if (!engine.getCaps().textureFloatRender) {
  82477. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82478. if (!engine.getCaps().textureHalfFloatRender) {
  82479. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82480. }
  82481. }
  82482. var cubeWidth = internalTexture.width;
  82483. var hostingScene = new BABYLON.Scene(engine);
  82484. var specularTextures = {};
  82485. var promises = [];
  82486. // Read and collect all mipmaps data from the cube.
  82487. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82488. mipmapsCount = Math.round(mipmapsCount);
  82489. var _loop_1 = function (i) {
  82490. var faceWidth = Math.pow(2, mipmapsCount - i);
  82491. var _loop_2 = function (face) {
  82492. var data = texture.readPixels(face, i);
  82493. // Creates a temp texture with the face data.
  82494. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82495. // And rgbdEncode them.
  82496. var promise = new Promise(function (resolve, reject) {
  82497. 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);
  82498. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82499. rgbdPostProcess.onApply = function (effect) {
  82500. effect._bindTexture("textureSampler", tempTexture);
  82501. };
  82502. // As the process needs to happen on the main canvas, keep track of the current size
  82503. var currentW = engine.getRenderWidth();
  82504. var currentH = engine.getRenderHeight();
  82505. // Set the desired size for the texture
  82506. engine.setSize(faceWidth, faceWidth);
  82507. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82508. // Reading datas from WebGL
  82509. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82510. var fileReader = new FileReader();
  82511. fileReader.onload = function (event) {
  82512. var arrayBuffer = event.target.result;
  82513. specularTextures[i * 6 + face] = arrayBuffer;
  82514. resolve();
  82515. };
  82516. fileReader.readAsArrayBuffer(blob);
  82517. });
  82518. // Reapply the previous canvas size
  82519. engine.setSize(currentW, currentH);
  82520. });
  82521. });
  82522. promises.push(promise);
  82523. };
  82524. // All faces of the cube.
  82525. for (var face = 0; face < 6; face++) {
  82526. _loop_2(face);
  82527. }
  82528. };
  82529. for (var i = 0; i <= mipmapsCount; i++) {
  82530. _loop_1(i);
  82531. }
  82532. // Once all the textures haves been collected as RGBD stored in PNGs
  82533. return Promise.all(promises).then(function () {
  82534. // We can delete the hosting scene keeping track of all the creation objects
  82535. hostingScene.dispose();
  82536. // Creates the json header for the env texture
  82537. var info = {
  82538. version: 1,
  82539. width: cubeWidth,
  82540. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82541. specular: {
  82542. mipmaps: [],
  82543. lodGenerationScale: texture.lodGenerationScale
  82544. }
  82545. };
  82546. // Sets the specular image data information
  82547. var position = 0;
  82548. for (var i = 0; i <= mipmapsCount; i++) {
  82549. for (var face = 0; face < 6; face++) {
  82550. var byteLength = specularTextures[i * 6 + face].byteLength;
  82551. info.specular.mipmaps.push({
  82552. length: byteLength,
  82553. position: position
  82554. });
  82555. position += byteLength;
  82556. }
  82557. }
  82558. // Encode the JSON as an array buffer
  82559. var infoString = JSON.stringify(info);
  82560. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82561. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82562. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82563. infoView[i] = infoString.charCodeAt(i);
  82564. }
  82565. // Ends up with a null terminator for easier parsing
  82566. infoView[infoString.length] = 0x00;
  82567. // Computes the final required size and creates the storage
  82568. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82569. var finalBuffer = new ArrayBuffer(totalSize);
  82570. var finalBufferView = new Uint8Array(finalBuffer);
  82571. var dataView = new DataView(finalBuffer);
  82572. // Copy the magic bytes identifying the file in
  82573. var pos = 0;
  82574. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82575. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82576. }
  82577. // Add the json info
  82578. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82579. pos += infoBuffer.byteLength;
  82580. // Finally inserts the texture data
  82581. for (var i = 0; i <= mipmapsCount; i++) {
  82582. for (var face = 0; face < 6; face++) {
  82583. var dataBuffer = specularTextures[i * 6 + face];
  82584. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82585. pos += dataBuffer.byteLength;
  82586. }
  82587. }
  82588. // Voila
  82589. return finalBuffer;
  82590. });
  82591. };
  82592. /**
  82593. * Creates a JSON representation of the spherical data.
  82594. * @param texture defines the texture containing the polynomials
  82595. * @return the JSON representation of the spherical info
  82596. */
  82597. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82598. var polynmials = texture.sphericalPolynomial;
  82599. if (polynmials == null) {
  82600. return null;
  82601. }
  82602. return {
  82603. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82604. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82605. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82606. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82607. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82608. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82609. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82610. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82611. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82612. };
  82613. };
  82614. /**
  82615. * Uploads the texture info contained in the env file to the GPU.
  82616. * @param texture defines the internal texture to upload to
  82617. * @param arrayBuffer defines the buffer cotaining the data to load
  82618. * @param info defines the texture info retrieved through the GetEnvInfo method
  82619. * @returns a promise
  82620. */
  82621. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82622. if (info.version !== 1) {
  82623. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  82624. }
  82625. var specularInfo = info.specular;
  82626. if (!specularInfo) {
  82627. // Nothing else parsed so far
  82628. return Promise.resolve();
  82629. }
  82630. // Double checks the enclosed info
  82631. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82632. mipmapsCount = Math.round(mipmapsCount) + 1;
  82633. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82634. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  82635. }
  82636. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  82637. var imageData = new Array(mipmapsCount);
  82638. for (var i = 0; i < mipmapsCount; i++) {
  82639. imageData[i] = new Array(6);
  82640. for (var face = 0; face < 6; face++) {
  82641. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82642. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82643. }
  82644. }
  82645. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82646. };
  82647. /**
  82648. * Uploads the levels of image data to the GPU.
  82649. * @param texture defines the internal texture to upload to
  82650. * @param imageData defines the array buffer views of image data [mipmap][face]
  82651. * @returns a promise
  82652. */
  82653. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82654. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  82655. throw new Error("Texture size must be a power of two");
  82656. }
  82657. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  82658. // Gets everything ready.
  82659. var engine = texture.getEngine();
  82660. var expandTexture = false;
  82661. var generateNonLODTextures = false;
  82662. var rgbdPostProcess = null;
  82663. var cubeRtt = null;
  82664. var lodTextures = null;
  82665. var caps = engine.getCaps();
  82666. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82667. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82668. texture.generateMipMaps = true;
  82669. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  82670. // Add extra process if texture lod is not supported
  82671. if (!caps.textureLOD) {
  82672. expandTexture = false;
  82673. generateNonLODTextures = true;
  82674. lodTextures = {};
  82675. }
  82676. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82677. else if (engine.webGLVersion < 2) {
  82678. expandTexture = false;
  82679. }
  82680. // If half float available we can uncompress the texture
  82681. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82682. expandTexture = true;
  82683. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82684. }
  82685. // If full float available we can uncompress the texture
  82686. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82687. expandTexture = true;
  82688. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82689. }
  82690. // Expand the texture if possible
  82691. if (expandTexture) {
  82692. // Simply run through the decode PP
  82693. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82694. texture._isRGBD = false;
  82695. texture.invertY = false;
  82696. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82697. generateDepthBuffer: false,
  82698. generateMipMaps: true,
  82699. generateStencilBuffer: false,
  82700. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82701. type: texture.type,
  82702. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82703. });
  82704. }
  82705. else {
  82706. texture._isRGBD = true;
  82707. texture.invertY = true;
  82708. // In case of missing support, applies the same patch than DDS files.
  82709. if (generateNonLODTextures) {
  82710. var mipSlices = 3;
  82711. var scale = texture._lodGenerationScale;
  82712. var offset = texture._lodGenerationOffset;
  82713. for (var i = 0; i < mipSlices; i++) {
  82714. //compute LOD from even spacing in smoothness (matching shader calculation)
  82715. var smoothness = i / (mipSlices - 1);
  82716. var roughness = 1 - smoothness;
  82717. var minLODIndex = offset; // roughness = 0
  82718. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  82719. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82720. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82721. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82722. glTextureFromLod.isCube = true;
  82723. glTextureFromLod.invertY = true;
  82724. glTextureFromLod.generateMipMaps = false;
  82725. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82726. // Wrap in a base texture for easy binding.
  82727. var lodTexture = new BABYLON.BaseTexture(null);
  82728. lodTexture.isCube = true;
  82729. lodTexture._texture = glTextureFromLod;
  82730. lodTextures[mipmapIndex] = lodTexture;
  82731. switch (i) {
  82732. case 0:
  82733. texture._lodTextureLow = lodTexture;
  82734. break;
  82735. case 1:
  82736. texture._lodTextureMid = lodTexture;
  82737. break;
  82738. case 2:
  82739. texture._lodTextureHigh = lodTexture;
  82740. break;
  82741. }
  82742. }
  82743. }
  82744. }
  82745. var promises = [];
  82746. var _loop_3 = function (i) {
  82747. var _loop_4 = function (face) {
  82748. // Constructs an image element from image data
  82749. var bytes = imageData[i][face];
  82750. var blob = new Blob([bytes], { type: 'image/png' });
  82751. var url = URL.createObjectURL(blob);
  82752. var image = new Image();
  82753. image.src = url;
  82754. // Enqueue promise to upload to the texture.
  82755. var promise = new Promise(function (resolve, reject) {
  82756. image.onload = function () {
  82757. if (expandTexture) {
  82758. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82759. reject(message);
  82760. }, image);
  82761. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82762. // Uncompress the data to a RTT
  82763. rgbdPostProcess.onApply = function (effect) {
  82764. effect._bindTexture("textureSampler", tempTexture_1);
  82765. effect.setFloat2("scale", 1, 1);
  82766. };
  82767. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82768. // Cleanup
  82769. engine.restoreDefaultFramebuffer();
  82770. tempTexture_1.dispose();
  82771. window.URL.revokeObjectURL(url);
  82772. resolve();
  82773. });
  82774. }
  82775. else {
  82776. engine._uploadImageToTexture(texture, image, face, i);
  82777. // Upload the face to the non lod texture support
  82778. if (generateNonLODTextures) {
  82779. var lodTexture = lodTextures[i];
  82780. if (lodTexture) {
  82781. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  82782. }
  82783. }
  82784. resolve();
  82785. }
  82786. };
  82787. image.onerror = function (error) {
  82788. reject(error);
  82789. };
  82790. });
  82791. promises.push(promise);
  82792. };
  82793. // All faces
  82794. for (var face = 0; face < 6; face++) {
  82795. _loop_4(face);
  82796. }
  82797. };
  82798. // All mipmaps up to provided number of images
  82799. for (var i = 0; i < imageData.length; i++) {
  82800. _loop_3(i);
  82801. }
  82802. // Fill remaining mipmaps with black textures.
  82803. if (imageData.length < mipmapsCount) {
  82804. var data = void 0;
  82805. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  82806. var dataLength = size * size * 4;
  82807. switch (texture.type) {
  82808. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  82809. data = new Uint8Array(dataLength);
  82810. break;
  82811. }
  82812. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  82813. data = new Uint16Array(dataLength);
  82814. break;
  82815. }
  82816. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  82817. data = new Float32Array(dataLength);
  82818. break;
  82819. }
  82820. }
  82821. for (var i = imageData.length; i < mipmapsCount; i++) {
  82822. for (var face = 0; face < 6; face++) {
  82823. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  82824. }
  82825. }
  82826. }
  82827. // Once all done, finishes the cleanup and return
  82828. return Promise.all(promises).then(function () {
  82829. // Release temp RTT.
  82830. if (cubeRtt) {
  82831. engine._releaseFramebufferObjects(cubeRtt);
  82832. cubeRtt._swapAndDie(texture);
  82833. }
  82834. // Release temp Post Process.
  82835. if (rgbdPostProcess) {
  82836. rgbdPostProcess.dispose();
  82837. }
  82838. // Flag internal texture as ready in case they are in use.
  82839. if (generateNonLODTextures) {
  82840. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82841. texture._lodTextureHigh._texture.isReady = true;
  82842. }
  82843. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82844. texture._lodTextureMid._texture.isReady = true;
  82845. }
  82846. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82847. texture._lodTextureLow._texture.isReady = true;
  82848. }
  82849. }
  82850. });
  82851. };
  82852. /**
  82853. * Uploads spherical polynomials information to the texture.
  82854. * @param texture defines the texture we are trying to upload the information to
  82855. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82856. */
  82857. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  82858. if (info.version !== 1) {
  82859. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82860. }
  82861. var irradianceInfo = info.irradiance;
  82862. if (!irradianceInfo) {
  82863. return;
  82864. }
  82865. var sp = new BABYLON.SphericalPolynomial();
  82866. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  82867. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  82868. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  82869. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  82870. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  82871. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  82872. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  82873. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  82874. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  82875. texture._sphericalPolynomial = sp;
  82876. };
  82877. /**
  82878. * Magic number identifying the env file.
  82879. */
  82880. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82881. return EnvironmentTextureTools;
  82882. }());
  82883. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82884. })(BABYLON || (BABYLON = {}));
  82885. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82886. var BABYLON;
  82887. (function (BABYLON) {
  82888. /**
  82889. * This represents a texture coming from an HDR input.
  82890. *
  82891. * The only supported format is currently panorama picture stored in RGBE format.
  82892. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82893. */
  82894. var HDRCubeTexture = /** @class */ (function (_super) {
  82895. __extends(HDRCubeTexture, _super);
  82896. /**
  82897. * Instantiates an HDRTexture from the following parameters.
  82898. *
  82899. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82900. * @param scene The scene the texture will be used in
  82901. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82902. * @param noMipmap Forces to not generate the mipmap if true
  82903. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82904. * @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)
  82905. * @param reserved Reserved flag for internal use.
  82906. */
  82907. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82908. if (noMipmap === void 0) { noMipmap = false; }
  82909. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82910. if (gammaSpace === void 0) { gammaSpace = false; }
  82911. if (reserved === void 0) { reserved = false; }
  82912. if (onLoad === void 0) { onLoad = null; }
  82913. if (onError === void 0) { onError = null; }
  82914. var _this = _super.call(this, scene) || this;
  82915. _this._generateHarmonics = true;
  82916. _this._onLoad = null;
  82917. _this._onError = null;
  82918. /**
  82919. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82920. */
  82921. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82922. _this._isBlocking = true;
  82923. _this._rotationY = 0;
  82924. /**
  82925. * Gets or sets the center of the bounding box associated with the cube texture
  82926. * It must define where the camera used to render the texture was set
  82927. */
  82928. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82929. if (!url) {
  82930. return _this;
  82931. }
  82932. _this.name = url;
  82933. _this.url = url;
  82934. _this.hasAlpha = false;
  82935. _this.isCube = true;
  82936. _this._textureMatrix = BABYLON.Matrix.Identity();
  82937. _this._onLoad = onLoad;
  82938. _this._onError = onError;
  82939. _this.gammaSpace = gammaSpace;
  82940. _this._noMipmap = noMipmap;
  82941. _this._size = size;
  82942. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82943. if (!_this._texture) {
  82944. if (!scene.useDelayedTextureLoading) {
  82945. _this.loadTexture();
  82946. }
  82947. else {
  82948. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82949. }
  82950. }
  82951. return _this;
  82952. }
  82953. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82954. /**
  82955. * Gets wether or not the texture is blocking during loading.
  82956. */
  82957. get: function () {
  82958. return this._isBlocking;
  82959. },
  82960. /**
  82961. * Sets wether or not the texture is blocking during loading.
  82962. */
  82963. set: function (value) {
  82964. this._isBlocking = value;
  82965. },
  82966. enumerable: true,
  82967. configurable: true
  82968. });
  82969. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82970. /**
  82971. * Gets texture matrix rotation angle around Y axis radians.
  82972. */
  82973. get: function () {
  82974. return this._rotationY;
  82975. },
  82976. /**
  82977. * Sets texture matrix rotation angle around Y axis in radians.
  82978. */
  82979. set: function (value) {
  82980. this._rotationY = value;
  82981. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82982. },
  82983. enumerable: true,
  82984. configurable: true
  82985. });
  82986. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82987. get: function () {
  82988. return this._boundingBoxSize;
  82989. },
  82990. /**
  82991. * Gets or sets the size of the bounding box associated with the cube texture
  82992. * When defined, the cubemap will switch to local mode
  82993. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82994. * @example https://www.babylonjs-playground.com/#RNASML
  82995. */
  82996. set: function (value) {
  82997. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82998. return;
  82999. }
  83000. this._boundingBoxSize = value;
  83001. var scene = this.getScene();
  83002. if (scene) {
  83003. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83004. }
  83005. },
  83006. enumerable: true,
  83007. configurable: true
  83008. });
  83009. /**
  83010. * Occurs when the file is raw .hdr file.
  83011. */
  83012. HDRCubeTexture.prototype.loadTexture = function () {
  83013. var _this = this;
  83014. var callback = function (buffer) {
  83015. _this.lodGenerationOffset = 0.0;
  83016. _this.lodGenerationScale = 0.8;
  83017. var scene = _this.getScene();
  83018. if (!scene) {
  83019. return null;
  83020. }
  83021. // Extract the raw linear data.
  83022. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83023. // Generate harmonics if needed.
  83024. if (_this._generateHarmonics) {
  83025. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83026. _this.sphericalPolynomial = sphericalPolynomial;
  83027. }
  83028. var results = [];
  83029. var byteArray = null;
  83030. // Push each faces.
  83031. for (var j = 0; j < 6; j++) {
  83032. // Create uintarray fallback.
  83033. if (!scene.getEngine().getCaps().textureFloat) {
  83034. // 3 channels of 1 bytes per pixel in bytes.
  83035. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83036. byteArray = new Uint8Array(byteBuffer);
  83037. }
  83038. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83039. // If special cases.
  83040. if (_this.gammaSpace || byteArray) {
  83041. for (var i = 0; i < _this._size * _this._size; i++) {
  83042. // Put in gamma space if requested.
  83043. if (_this.gammaSpace) {
  83044. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83045. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83046. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83047. }
  83048. // Convert to int texture for fallback.
  83049. if (byteArray) {
  83050. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83051. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83052. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83053. // May use luminance instead if the result is not accurate.
  83054. var max = Math.max(Math.max(r, g), b);
  83055. if (max > 255) {
  83056. var scale = 255 / max;
  83057. r *= scale;
  83058. g *= scale;
  83059. b *= scale;
  83060. }
  83061. byteArray[(i * 3) + 0] = r;
  83062. byteArray[(i * 3) + 1] = g;
  83063. byteArray[(i * 3) + 2] = b;
  83064. }
  83065. }
  83066. }
  83067. if (byteArray) {
  83068. results.push(byteArray);
  83069. }
  83070. else {
  83071. results.push(dataFace);
  83072. }
  83073. }
  83074. return results;
  83075. };
  83076. var scene = this.getScene();
  83077. if (scene) {
  83078. 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);
  83079. }
  83080. };
  83081. HDRCubeTexture.prototype.clone = function () {
  83082. var scene = this.getScene();
  83083. if (!scene) {
  83084. return this;
  83085. }
  83086. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83087. // Base texture
  83088. newTexture.level = this.level;
  83089. newTexture.wrapU = this.wrapU;
  83090. newTexture.wrapV = this.wrapV;
  83091. newTexture.coordinatesIndex = this.coordinatesIndex;
  83092. newTexture.coordinatesMode = this.coordinatesMode;
  83093. return newTexture;
  83094. };
  83095. // Methods
  83096. HDRCubeTexture.prototype.delayLoad = function () {
  83097. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83098. return;
  83099. }
  83100. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83101. this._texture = this._getFromCache(this.url, this._noMipmap);
  83102. if (!this._texture) {
  83103. this.loadTexture();
  83104. }
  83105. };
  83106. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83107. return this._textureMatrix;
  83108. };
  83109. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83110. this._textureMatrix = value;
  83111. };
  83112. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83113. var texture = null;
  83114. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83115. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83116. texture.name = parsedTexture.name;
  83117. texture.hasAlpha = parsedTexture.hasAlpha;
  83118. texture.level = parsedTexture.level;
  83119. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83120. texture.isBlocking = parsedTexture.isBlocking;
  83121. }
  83122. if (texture) {
  83123. if (parsedTexture.boundingBoxPosition) {
  83124. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83125. }
  83126. if (parsedTexture.boundingBoxSize) {
  83127. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83128. }
  83129. if (parsedTexture.rotationY) {
  83130. texture.rotationY = parsedTexture.rotationY;
  83131. }
  83132. }
  83133. return texture;
  83134. };
  83135. HDRCubeTexture.prototype.serialize = function () {
  83136. if (!this.name) {
  83137. return null;
  83138. }
  83139. var serializationObject = {};
  83140. serializationObject.name = this.name;
  83141. serializationObject.hasAlpha = this.hasAlpha;
  83142. serializationObject.isCube = true;
  83143. serializationObject.level = this.level;
  83144. serializationObject.size = this._size;
  83145. serializationObject.coordinatesMode = this.coordinatesMode;
  83146. serializationObject.useInGammaSpace = this.gammaSpace;
  83147. serializationObject.generateHarmonics = this._generateHarmonics;
  83148. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83149. serializationObject.noMipmap = this._noMipmap;
  83150. serializationObject.isBlocking = this._isBlocking;
  83151. serializationObject.rotationY = this._rotationY;
  83152. return serializationObject;
  83153. };
  83154. HDRCubeTexture._facesMapping = [
  83155. "right",
  83156. "left",
  83157. "up",
  83158. "down",
  83159. "front",
  83160. "back"
  83161. ];
  83162. return HDRCubeTexture;
  83163. }(BABYLON.BaseTexture));
  83164. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83165. })(BABYLON || (BABYLON = {}));
  83166. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83167. var BABYLON;
  83168. (function (BABYLON) {
  83169. var IndexedVector2 = /** @class */ (function (_super) {
  83170. __extends(IndexedVector2, _super);
  83171. function IndexedVector2(original, index) {
  83172. var _this = _super.call(this, original.x, original.y) || this;
  83173. _this.index = index;
  83174. return _this;
  83175. }
  83176. return IndexedVector2;
  83177. }(BABYLON.Vector2));
  83178. var PolygonPoints = /** @class */ (function () {
  83179. function PolygonPoints() {
  83180. this.elements = new Array();
  83181. }
  83182. PolygonPoints.prototype.add = function (originalPoints) {
  83183. var _this = this;
  83184. var result = new Array();
  83185. originalPoints.forEach(function (point) {
  83186. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83187. var newPoint = new IndexedVector2(point, _this.elements.length);
  83188. result.push(newPoint);
  83189. _this.elements.push(newPoint);
  83190. }
  83191. });
  83192. return result;
  83193. };
  83194. PolygonPoints.prototype.computeBounds = function () {
  83195. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83196. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83197. this.elements.forEach(function (point) {
  83198. // x
  83199. if (point.x < lmin.x) {
  83200. lmin.x = point.x;
  83201. }
  83202. else if (point.x > lmax.x) {
  83203. lmax.x = point.x;
  83204. }
  83205. // y
  83206. if (point.y < lmin.y) {
  83207. lmin.y = point.y;
  83208. }
  83209. else if (point.y > lmax.y) {
  83210. lmax.y = point.y;
  83211. }
  83212. });
  83213. return {
  83214. min: lmin,
  83215. max: lmax,
  83216. width: lmax.x - lmin.x,
  83217. height: lmax.y - lmin.y
  83218. };
  83219. };
  83220. return PolygonPoints;
  83221. }());
  83222. var Polygon = /** @class */ (function () {
  83223. function Polygon() {
  83224. }
  83225. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83226. return [
  83227. new BABYLON.Vector2(xmin, ymin),
  83228. new BABYLON.Vector2(xmax, ymin),
  83229. new BABYLON.Vector2(xmax, ymax),
  83230. new BABYLON.Vector2(xmin, ymax)
  83231. ];
  83232. };
  83233. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83234. if (cx === void 0) { cx = 0; }
  83235. if (cy === void 0) { cy = 0; }
  83236. if (numberOfSides === void 0) { numberOfSides = 32; }
  83237. var result = new Array();
  83238. var angle = 0;
  83239. var increment = (Math.PI * 2) / numberOfSides;
  83240. for (var i = 0; i < numberOfSides; i++) {
  83241. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83242. angle -= increment;
  83243. }
  83244. return result;
  83245. };
  83246. Polygon.Parse = function (input) {
  83247. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83248. var i, result = [];
  83249. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83250. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83251. }
  83252. return result;
  83253. };
  83254. Polygon.StartingAt = function (x, y) {
  83255. return BABYLON.Path2.StartingAt(x, y);
  83256. };
  83257. return Polygon;
  83258. }());
  83259. BABYLON.Polygon = Polygon;
  83260. var PolygonMeshBuilder = /** @class */ (function () {
  83261. function PolygonMeshBuilder(name, contours, scene) {
  83262. this._points = new PolygonPoints();
  83263. this._outlinepoints = new PolygonPoints();
  83264. this._holes = new Array();
  83265. this._epoints = new Array();
  83266. this._eholes = new Array();
  83267. this._name = name;
  83268. this._scene = scene;
  83269. var points;
  83270. if (contours instanceof BABYLON.Path2) {
  83271. points = contours.getPoints();
  83272. }
  83273. else {
  83274. points = contours;
  83275. }
  83276. this._addToepoint(points);
  83277. this._points.add(points);
  83278. this._outlinepoints.add(points);
  83279. if (typeof earcut === 'undefined') {
  83280. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83281. }
  83282. }
  83283. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83284. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83285. var p = points_1[_i];
  83286. this._epoints.push(p.x, p.y);
  83287. }
  83288. };
  83289. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83290. this._points.add(hole);
  83291. var holepoints = new PolygonPoints();
  83292. holepoints.add(hole);
  83293. this._holes.push(holepoints);
  83294. this._eholes.push(this._epoints.length / 2);
  83295. this._addToepoint(hole);
  83296. return this;
  83297. };
  83298. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83299. var _this = this;
  83300. if (updatable === void 0) { updatable = false; }
  83301. if (depth === void 0) { depth = 0; }
  83302. var result = new BABYLON.Mesh(this._name, this._scene);
  83303. var normals = new Array();
  83304. var positions = new Array();
  83305. var uvs = new Array();
  83306. var bounds = this._points.computeBounds();
  83307. this._points.elements.forEach(function (p) {
  83308. normals.push(0, 1.0, 0);
  83309. positions.push(p.x, 0, p.y);
  83310. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83311. });
  83312. var indices = new Array();
  83313. var res = earcut(this._epoints, this._eholes, 2);
  83314. for (var i = 0; i < res.length; i++) {
  83315. indices.push(res[i]);
  83316. }
  83317. if (depth > 0) {
  83318. var positionscount = (positions.length / 3); //get the current pointcount
  83319. this._points.elements.forEach(function (p) {
  83320. normals.push(0, -1.0, 0);
  83321. positions.push(p.x, -depth, p.y);
  83322. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83323. });
  83324. var totalCount = indices.length;
  83325. for (var i = 0; i < totalCount; i += 3) {
  83326. var i0 = indices[i + 0];
  83327. var i1 = indices[i + 1];
  83328. var i2 = indices[i + 2];
  83329. indices.push(i2 + positionscount);
  83330. indices.push(i1 + positionscount);
  83331. indices.push(i0 + positionscount);
  83332. }
  83333. //Add the sides
  83334. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83335. this._holes.forEach(function (hole) {
  83336. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83337. });
  83338. }
  83339. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83340. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83341. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83342. result.setIndices(indices);
  83343. return result;
  83344. };
  83345. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83346. var StartIndex = positions.length / 3;
  83347. var ulength = 0;
  83348. for (var i = 0; i < points.elements.length; i++) {
  83349. var p = points.elements[i];
  83350. var p1;
  83351. if ((i + 1) > points.elements.length - 1) {
  83352. p1 = points.elements[0];
  83353. }
  83354. else {
  83355. p1 = points.elements[i + 1];
  83356. }
  83357. positions.push(p.x, 0, p.y);
  83358. positions.push(p.x, -depth, p.y);
  83359. positions.push(p1.x, 0, p1.y);
  83360. positions.push(p1.x, -depth, p1.y);
  83361. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83362. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83363. var v3 = v2.subtract(v1);
  83364. var v4 = new BABYLON.Vector3(0, 1, 0);
  83365. var vn = BABYLON.Vector3.Cross(v3, v4);
  83366. vn = vn.normalize();
  83367. uvs.push(ulength / bounds.width, 0);
  83368. uvs.push(ulength / bounds.width, 1);
  83369. ulength += v3.length();
  83370. uvs.push((ulength / bounds.width), 0);
  83371. uvs.push((ulength / bounds.width), 1);
  83372. if (!flip) {
  83373. normals.push(-vn.x, -vn.y, -vn.z);
  83374. normals.push(-vn.x, -vn.y, -vn.z);
  83375. normals.push(-vn.x, -vn.y, -vn.z);
  83376. normals.push(-vn.x, -vn.y, -vn.z);
  83377. indices.push(StartIndex);
  83378. indices.push(StartIndex + 1);
  83379. indices.push(StartIndex + 2);
  83380. indices.push(StartIndex + 1);
  83381. indices.push(StartIndex + 3);
  83382. indices.push(StartIndex + 2);
  83383. }
  83384. else {
  83385. normals.push(vn.x, vn.y, vn.z);
  83386. normals.push(vn.x, vn.y, vn.z);
  83387. normals.push(vn.x, vn.y, vn.z);
  83388. normals.push(vn.x, vn.y, vn.z);
  83389. indices.push(StartIndex);
  83390. indices.push(StartIndex + 2);
  83391. indices.push(StartIndex + 1);
  83392. indices.push(StartIndex + 1);
  83393. indices.push(StartIndex + 2);
  83394. indices.push(StartIndex + 3);
  83395. }
  83396. StartIndex += 4;
  83397. }
  83398. ;
  83399. };
  83400. return PolygonMeshBuilder;
  83401. }());
  83402. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83403. })(BABYLON || (BABYLON = {}));
  83404. //# sourceMappingURL=babylon.polygonMesh.js.map
  83405. var BABYLON;
  83406. (function (BABYLON) {
  83407. // Unique ID when we import meshes from Babylon to CSG
  83408. var currentCSGMeshId = 0;
  83409. // # class Vertex
  83410. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83411. // one to provide additional features like texture coordinates and vertex
  83412. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83413. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83414. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83415. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83416. // is not used anywhere else.
  83417. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83418. var Vertex = /** @class */ (function () {
  83419. function Vertex(pos, normal, uv) {
  83420. this.pos = pos;
  83421. this.normal = normal;
  83422. this.uv = uv;
  83423. }
  83424. Vertex.prototype.clone = function () {
  83425. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83426. };
  83427. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83428. // orientation of a polygon is flipped.
  83429. Vertex.prototype.flip = function () {
  83430. this.normal = this.normal.scale(-1);
  83431. };
  83432. // Create a new vertex between this vertex and `other` by linearly
  83433. // interpolating all properties using a parameter of `t`. Subclasses should
  83434. // override this to interpolate additional properties.
  83435. Vertex.prototype.interpolate = function (other, t) {
  83436. 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));
  83437. };
  83438. return Vertex;
  83439. }());
  83440. // # class Plane
  83441. // Represents a plane in 3D space.
  83442. var Plane = /** @class */ (function () {
  83443. function Plane(normal, w) {
  83444. this.normal = normal;
  83445. this.w = w;
  83446. }
  83447. Plane.FromPoints = function (a, b, c) {
  83448. var v0 = c.subtract(a);
  83449. var v1 = b.subtract(a);
  83450. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83451. return null;
  83452. }
  83453. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83454. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83455. };
  83456. Plane.prototype.clone = function () {
  83457. return new Plane(this.normal.clone(), this.w);
  83458. };
  83459. Plane.prototype.flip = function () {
  83460. this.normal.scaleInPlace(-1);
  83461. this.w = -this.w;
  83462. };
  83463. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83464. // fragments in the appropriate lists. Coplanar polygons go into either
  83465. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83466. // respect to this plane. Polygons in front or in back of this plane go into
  83467. // either `front` or `back`.
  83468. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83469. var COPLANAR = 0;
  83470. var FRONT = 1;
  83471. var BACK = 2;
  83472. var SPANNING = 3;
  83473. // Classify each point as well as the entire polygon into one of the above
  83474. // four classes.
  83475. var polygonType = 0;
  83476. var types = [];
  83477. var i;
  83478. var t;
  83479. for (i = 0; i < polygon.vertices.length; i++) {
  83480. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83481. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83482. polygonType |= type;
  83483. types.push(type);
  83484. }
  83485. // Put the polygon in the correct list, splitting it when necessary.
  83486. switch (polygonType) {
  83487. case COPLANAR:
  83488. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83489. break;
  83490. case FRONT:
  83491. front.push(polygon);
  83492. break;
  83493. case BACK:
  83494. back.push(polygon);
  83495. break;
  83496. case SPANNING:
  83497. var f = [], b = [];
  83498. for (i = 0; i < polygon.vertices.length; i++) {
  83499. var j = (i + 1) % polygon.vertices.length;
  83500. var ti = types[i], tj = types[j];
  83501. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83502. if (ti !== BACK)
  83503. f.push(vi);
  83504. if (ti !== FRONT)
  83505. b.push(ti !== BACK ? vi.clone() : vi);
  83506. if ((ti | tj) === SPANNING) {
  83507. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83508. var v = vi.interpolate(vj, t);
  83509. f.push(v);
  83510. b.push(v.clone());
  83511. }
  83512. }
  83513. var poly;
  83514. if (f.length >= 3) {
  83515. poly = new Polygon(f, polygon.shared);
  83516. if (poly.plane)
  83517. front.push(poly);
  83518. }
  83519. if (b.length >= 3) {
  83520. poly = new Polygon(b, polygon.shared);
  83521. if (poly.plane)
  83522. back.push(poly);
  83523. }
  83524. break;
  83525. }
  83526. };
  83527. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83528. // point is on the plane.
  83529. Plane.EPSILON = 1e-5;
  83530. return Plane;
  83531. }());
  83532. // # class Polygon
  83533. // Represents a convex polygon. The vertices used to initialize a polygon must
  83534. // be coplanar and form a convex loop.
  83535. //
  83536. // Each convex polygon has a `shared` property, which is shared between all
  83537. // polygons that are clones of each other or were split from the same polygon.
  83538. // This can be used to define per-polygon properties (such as surface color).
  83539. var Polygon = /** @class */ (function () {
  83540. function Polygon(vertices, shared) {
  83541. this.vertices = vertices;
  83542. this.shared = shared;
  83543. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83544. }
  83545. Polygon.prototype.clone = function () {
  83546. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83547. return new Polygon(vertices, this.shared);
  83548. };
  83549. Polygon.prototype.flip = function () {
  83550. this.vertices.reverse().map(function (v) { v.flip(); });
  83551. this.plane.flip();
  83552. };
  83553. return Polygon;
  83554. }());
  83555. // # class Node
  83556. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83557. // by picking a polygon to split along. That polygon (and all other coplanar
  83558. // polygons) are added directly to that node and the other polygons are added to
  83559. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83560. // no distinction between internal and leaf nodes.
  83561. var Node = /** @class */ (function () {
  83562. function Node(polygons) {
  83563. this.plane = null;
  83564. this.front = null;
  83565. this.back = null;
  83566. this.polygons = new Array();
  83567. if (polygons) {
  83568. this.build(polygons);
  83569. }
  83570. }
  83571. Node.prototype.clone = function () {
  83572. var node = new Node();
  83573. node.plane = this.plane && this.plane.clone();
  83574. node.front = this.front && this.front.clone();
  83575. node.back = this.back && this.back.clone();
  83576. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83577. return node;
  83578. };
  83579. // Convert solid space to empty space and empty space to solid space.
  83580. Node.prototype.invert = function () {
  83581. for (var i = 0; i < this.polygons.length; i++) {
  83582. this.polygons[i].flip();
  83583. }
  83584. if (this.plane) {
  83585. this.plane.flip();
  83586. }
  83587. if (this.front) {
  83588. this.front.invert();
  83589. }
  83590. if (this.back) {
  83591. this.back.invert();
  83592. }
  83593. var temp = this.front;
  83594. this.front = this.back;
  83595. this.back = temp;
  83596. };
  83597. // Recursively remove all polygons in `polygons` that are inside this BSP
  83598. // tree.
  83599. Node.prototype.clipPolygons = function (polygons) {
  83600. if (!this.plane)
  83601. return polygons.slice();
  83602. var front = new Array(), back = new Array();
  83603. for (var i = 0; i < polygons.length; i++) {
  83604. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83605. }
  83606. if (this.front) {
  83607. front = this.front.clipPolygons(front);
  83608. }
  83609. if (this.back) {
  83610. back = this.back.clipPolygons(back);
  83611. }
  83612. else {
  83613. back = [];
  83614. }
  83615. return front.concat(back);
  83616. };
  83617. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83618. // `bsp`.
  83619. Node.prototype.clipTo = function (bsp) {
  83620. this.polygons = bsp.clipPolygons(this.polygons);
  83621. if (this.front)
  83622. this.front.clipTo(bsp);
  83623. if (this.back)
  83624. this.back.clipTo(bsp);
  83625. };
  83626. // Return a list of all polygons in this BSP tree.
  83627. Node.prototype.allPolygons = function () {
  83628. var polygons = this.polygons.slice();
  83629. if (this.front)
  83630. polygons = polygons.concat(this.front.allPolygons());
  83631. if (this.back)
  83632. polygons = polygons.concat(this.back.allPolygons());
  83633. return polygons;
  83634. };
  83635. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83636. // new polygons are filtered down to the bottom of the tree and become new
  83637. // nodes there. Each set of polygons is partitioned using the first polygon
  83638. // (no heuristic is used to pick a good split).
  83639. Node.prototype.build = function (polygons) {
  83640. if (!polygons.length)
  83641. return;
  83642. if (!this.plane)
  83643. this.plane = polygons[0].plane.clone();
  83644. var front = new Array(), back = new Array();
  83645. for (var i = 0; i < polygons.length; i++) {
  83646. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83647. }
  83648. if (front.length) {
  83649. if (!this.front)
  83650. this.front = new Node();
  83651. this.front.build(front);
  83652. }
  83653. if (back.length) {
  83654. if (!this.back)
  83655. this.back = new Node();
  83656. this.back.build(back);
  83657. }
  83658. };
  83659. return Node;
  83660. }());
  83661. var CSG = /** @class */ (function () {
  83662. function CSG() {
  83663. this.polygons = new Array();
  83664. }
  83665. // Convert BABYLON.Mesh to BABYLON.CSG
  83666. CSG.FromMesh = function (mesh) {
  83667. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83668. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83669. if (mesh instanceof BABYLON.Mesh) {
  83670. mesh.computeWorldMatrix(true);
  83671. matrix = mesh.getWorldMatrix();
  83672. meshPosition = mesh.position.clone();
  83673. meshRotation = mesh.rotation.clone();
  83674. if (mesh.rotationQuaternion) {
  83675. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83676. }
  83677. meshScaling = mesh.scaling.clone();
  83678. }
  83679. else {
  83680. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83681. }
  83682. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83683. var subMeshes = mesh.subMeshes;
  83684. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83685. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83686. vertices = [];
  83687. for (var j = 0; j < 3; j++) {
  83688. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83689. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83690. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83691. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83692. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83693. vertex = new Vertex(position, normal, uv);
  83694. vertices.push(vertex);
  83695. }
  83696. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83697. // To handle the case of degenerated triangle
  83698. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83699. if (polygon.plane)
  83700. polygons.push(polygon);
  83701. }
  83702. }
  83703. var csg = CSG.FromPolygons(polygons);
  83704. csg.matrix = matrix;
  83705. csg.position = meshPosition;
  83706. csg.rotation = meshRotation;
  83707. csg.scaling = meshScaling;
  83708. csg.rotationQuaternion = meshRotationQuaternion;
  83709. currentCSGMeshId++;
  83710. return csg;
  83711. };
  83712. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83713. CSG.FromPolygons = function (polygons) {
  83714. var csg = new CSG();
  83715. csg.polygons = polygons;
  83716. return csg;
  83717. };
  83718. CSG.prototype.clone = function () {
  83719. var csg = new CSG();
  83720. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83721. csg.copyTransformAttributes(this);
  83722. return csg;
  83723. };
  83724. CSG.prototype.union = function (csg) {
  83725. var a = new Node(this.clone().polygons);
  83726. var b = new Node(csg.clone().polygons);
  83727. a.clipTo(b);
  83728. b.clipTo(a);
  83729. b.invert();
  83730. b.clipTo(a);
  83731. b.invert();
  83732. a.build(b.allPolygons());
  83733. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83734. };
  83735. CSG.prototype.unionInPlace = function (csg) {
  83736. var a = new Node(this.polygons);
  83737. var b = new Node(csg.polygons);
  83738. a.clipTo(b);
  83739. b.clipTo(a);
  83740. b.invert();
  83741. b.clipTo(a);
  83742. b.invert();
  83743. a.build(b.allPolygons());
  83744. this.polygons = a.allPolygons();
  83745. };
  83746. CSG.prototype.subtract = function (csg) {
  83747. var a = new Node(this.clone().polygons);
  83748. var b = new Node(csg.clone().polygons);
  83749. a.invert();
  83750. a.clipTo(b);
  83751. b.clipTo(a);
  83752. b.invert();
  83753. b.clipTo(a);
  83754. b.invert();
  83755. a.build(b.allPolygons());
  83756. a.invert();
  83757. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83758. };
  83759. CSG.prototype.subtractInPlace = function (csg) {
  83760. var a = new Node(this.polygons);
  83761. var b = new Node(csg.polygons);
  83762. a.invert();
  83763. a.clipTo(b);
  83764. b.clipTo(a);
  83765. b.invert();
  83766. b.clipTo(a);
  83767. b.invert();
  83768. a.build(b.allPolygons());
  83769. a.invert();
  83770. this.polygons = a.allPolygons();
  83771. };
  83772. CSG.prototype.intersect = function (csg) {
  83773. var a = new Node(this.clone().polygons);
  83774. var b = new Node(csg.clone().polygons);
  83775. a.invert();
  83776. b.clipTo(a);
  83777. b.invert();
  83778. a.clipTo(b);
  83779. b.clipTo(a);
  83780. a.build(b.allPolygons());
  83781. a.invert();
  83782. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83783. };
  83784. CSG.prototype.intersectInPlace = function (csg) {
  83785. var a = new Node(this.polygons);
  83786. var b = new Node(csg.polygons);
  83787. a.invert();
  83788. b.clipTo(a);
  83789. b.invert();
  83790. a.clipTo(b);
  83791. b.clipTo(a);
  83792. a.build(b.allPolygons());
  83793. a.invert();
  83794. this.polygons = a.allPolygons();
  83795. };
  83796. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83797. // not modified.
  83798. CSG.prototype.inverse = function () {
  83799. var csg = this.clone();
  83800. csg.inverseInPlace();
  83801. return csg;
  83802. };
  83803. CSG.prototype.inverseInPlace = function () {
  83804. this.polygons.map(function (p) { p.flip(); });
  83805. };
  83806. // This is used to keep meshes transformations so they can be restored
  83807. // when we build back a Babylon Mesh
  83808. // NB : All CSG operations are performed in world coordinates
  83809. CSG.prototype.copyTransformAttributes = function (csg) {
  83810. this.matrix = csg.matrix;
  83811. this.position = csg.position;
  83812. this.rotation = csg.rotation;
  83813. this.scaling = csg.scaling;
  83814. this.rotationQuaternion = csg.rotationQuaternion;
  83815. return this;
  83816. };
  83817. // Build Raw mesh from CSG
  83818. // Coordinates here are in world space
  83819. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83820. var matrix = this.matrix.clone();
  83821. matrix.invert();
  83822. 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;
  83823. if (keepSubMeshes) {
  83824. // Sort Polygons, since subMeshes are indices range
  83825. polygons.sort(function (a, b) {
  83826. if (a.shared.meshId === b.shared.meshId) {
  83827. return a.shared.subMeshId - b.shared.subMeshId;
  83828. }
  83829. else {
  83830. return a.shared.meshId - b.shared.meshId;
  83831. }
  83832. });
  83833. }
  83834. for (var i = 0, il = polygons.length; i < il; i++) {
  83835. polygon = polygons[i];
  83836. // Building SubMeshes
  83837. if (!subMesh_dict[polygon.shared.meshId]) {
  83838. subMesh_dict[polygon.shared.meshId] = {};
  83839. }
  83840. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83841. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83842. indexStart: +Infinity,
  83843. indexEnd: -Infinity,
  83844. materialIndex: polygon.shared.materialIndex
  83845. };
  83846. }
  83847. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83848. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83849. polygonIndices[0] = 0;
  83850. polygonIndices[1] = j - 1;
  83851. polygonIndices[2] = j;
  83852. for (var k = 0; k < 3; k++) {
  83853. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83854. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83855. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83856. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83857. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83858. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83859. // Check if 2 points can be merged
  83860. if (!(typeof vertex_idx !== 'undefined' &&
  83861. normals[vertex_idx * 3] === localNormal.x &&
  83862. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83863. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83864. uvs[vertex_idx * 2] === uv.x &&
  83865. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83866. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83867. uvs.push(uv.x, uv.y);
  83868. normals.push(normal.x, normal.y, normal.z);
  83869. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83870. }
  83871. indices.push(vertex_idx);
  83872. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83873. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83874. currentIndex++;
  83875. }
  83876. }
  83877. }
  83878. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83879. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83880. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83881. mesh.setIndices(indices, null);
  83882. if (keepSubMeshes) {
  83883. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83884. var materialIndexOffset = 0, materialMaxIndex;
  83885. mesh.subMeshes = new Array();
  83886. for (var m in subMesh_dict) {
  83887. materialMaxIndex = -1;
  83888. for (var sm in subMesh_dict[m]) {
  83889. subMesh_obj = subMesh_dict[m][sm];
  83890. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83891. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83892. }
  83893. materialIndexOffset += ++materialMaxIndex;
  83894. }
  83895. }
  83896. return mesh;
  83897. };
  83898. // Build Mesh from CSG taking material and transforms into account
  83899. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83900. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83901. mesh.material = material;
  83902. mesh.position.copyFrom(this.position);
  83903. mesh.rotation.copyFrom(this.rotation);
  83904. if (this.rotationQuaternion) {
  83905. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83906. }
  83907. mesh.scaling.copyFrom(this.scaling);
  83908. mesh.computeWorldMatrix(true);
  83909. return mesh;
  83910. };
  83911. return CSG;
  83912. }());
  83913. BABYLON.CSG = CSG;
  83914. })(BABYLON || (BABYLON = {}));
  83915. //# sourceMappingURL=babylon.csg.js.map
  83916. var BABYLON;
  83917. (function (BABYLON) {
  83918. var LensFlare = /** @class */ (function () {
  83919. function LensFlare(size, position, color, imgUrl, system) {
  83920. this.size = size;
  83921. this.position = position;
  83922. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83923. this.color = color || new BABYLON.Color3(1, 1, 1);
  83924. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83925. this._system = system;
  83926. system.lensFlares.push(this);
  83927. }
  83928. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83929. return new LensFlare(size, position, color, imgUrl, system);
  83930. };
  83931. LensFlare.prototype.dispose = function () {
  83932. if (this.texture) {
  83933. this.texture.dispose();
  83934. }
  83935. // Remove from scene
  83936. var index = this._system.lensFlares.indexOf(this);
  83937. this._system.lensFlares.splice(index, 1);
  83938. };
  83939. ;
  83940. return LensFlare;
  83941. }());
  83942. BABYLON.LensFlare = LensFlare;
  83943. })(BABYLON || (BABYLON = {}));
  83944. //# sourceMappingURL=babylon.lensFlare.js.map
  83945. var BABYLON;
  83946. (function (BABYLON) {
  83947. // Adds the parser to the scene parsers.
  83948. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  83949. // Lens flares
  83950. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  83951. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  83952. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  83953. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  83954. container.lensFlareSystems.push(lf);
  83955. }
  83956. }
  83957. });
  83958. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  83959. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83960. if (this.lensFlareSystems[index].name === name) {
  83961. return this.lensFlareSystems[index];
  83962. }
  83963. }
  83964. return null;
  83965. };
  83966. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  83967. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83968. if (this.lensFlareSystems[index].id === id) {
  83969. return this.lensFlareSystems[index];
  83970. }
  83971. }
  83972. return null;
  83973. };
  83974. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  83975. var index = this.lensFlareSystems.indexOf(toRemove);
  83976. if (index !== -1) {
  83977. this.lensFlareSystems.splice(index, 1);
  83978. }
  83979. return index;
  83980. };
  83981. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  83982. this.lensFlareSystems.push(newLensFlareSystem);
  83983. };
  83984. /**
  83985. * Defines the lens flare scene component responsible to manage any lens flares
  83986. * in a given scene.
  83987. */
  83988. var LensFlareSystemSceneComponent = /** @class */ (function () {
  83989. /**
  83990. * Creates a new instance of the component for the given scene
  83991. * @param scene Defines the scene to register the component in
  83992. */
  83993. function LensFlareSystemSceneComponent(scene) {
  83994. /**
  83995. * The component name helpfull to identify the component in the list of scene components.
  83996. */
  83997. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  83998. this.scene = scene;
  83999. scene.lensFlareSystems = new Array();
  84000. }
  84001. /**
  84002. * Registers the component in a given scene
  84003. */
  84004. LensFlareSystemSceneComponent.prototype.register = function () {
  84005. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84006. };
  84007. /**
  84008. * Rebuilds the elements related to this component in case of
  84009. * context lost for instance.
  84010. */
  84011. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84012. // Nothing to do for lens flare
  84013. };
  84014. /**
  84015. * Adds all the element from the container to the scene
  84016. * @param container the container holding the elements
  84017. */
  84018. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84019. var _this = this;
  84020. if (!container.lensFlareSystems) {
  84021. return;
  84022. }
  84023. container.lensFlareSystems.forEach(function (o) {
  84024. _this.scene.addLensFlareSystem(o);
  84025. });
  84026. };
  84027. /**
  84028. * Removes all the elements in the container from the scene
  84029. * @param container contains the elements to remove
  84030. */
  84031. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84032. var _this = this;
  84033. if (!container.lensFlareSystems) {
  84034. return;
  84035. }
  84036. container.lensFlareSystems.forEach(function (o) {
  84037. _this.scene.removeLensFlareSystem(o);
  84038. });
  84039. };
  84040. /**
  84041. * Serializes the component data to the specified json object
  84042. * @param serializationObject The object to serialize to
  84043. */
  84044. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84045. // Lens flares
  84046. serializationObject.lensFlareSystems = [];
  84047. var lensFlareSystems = this.scene.lensFlareSystems;
  84048. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84049. var lensFlareSystem = lensFlareSystems_1[_i];
  84050. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84051. }
  84052. };
  84053. /**
  84054. * Disposes the component and the associated ressources.
  84055. */
  84056. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84057. var lensFlareSystems = this.scene.lensFlareSystems;
  84058. while (lensFlareSystems.length) {
  84059. lensFlareSystems[0].dispose();
  84060. }
  84061. };
  84062. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84063. // Lens flares
  84064. if (this.scene.lensFlaresEnabled) {
  84065. var lensFlareSystems = this.scene.lensFlareSystems;
  84066. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84067. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84068. var lensFlareSystem = lensFlareSystems_2[_i];
  84069. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84070. lensFlareSystem.render();
  84071. }
  84072. }
  84073. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84074. }
  84075. };
  84076. return LensFlareSystemSceneComponent;
  84077. }());
  84078. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84079. })(BABYLON || (BABYLON = {}));
  84080. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84081. var BABYLON;
  84082. (function (BABYLON) {
  84083. var LensFlareSystem = /** @class */ (function () {
  84084. function LensFlareSystem(name, emitter, scene) {
  84085. this.name = name;
  84086. this.lensFlares = new Array();
  84087. this.borderLimit = 300;
  84088. this.viewportBorder = 0;
  84089. this.layerMask = 0x0FFFFFFF;
  84090. this._vertexBuffers = {};
  84091. this._isEnabled = true;
  84092. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84093. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84094. if (!component) {
  84095. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84096. scene._addComponent(component);
  84097. }
  84098. this._emitter = emitter;
  84099. this.id = name;
  84100. scene.lensFlareSystems.push(this);
  84101. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84102. var engine = scene.getEngine();
  84103. // VBO
  84104. var vertices = [];
  84105. vertices.push(1, 1);
  84106. vertices.push(-1, 1);
  84107. vertices.push(-1, -1);
  84108. vertices.push(1, -1);
  84109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84110. // Indices
  84111. var indices = [];
  84112. indices.push(0);
  84113. indices.push(1);
  84114. indices.push(2);
  84115. indices.push(0);
  84116. indices.push(2);
  84117. indices.push(3);
  84118. this._indexBuffer = engine.createIndexBuffer(indices);
  84119. // Effects
  84120. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84121. }
  84122. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84123. get: function () {
  84124. return this._isEnabled;
  84125. },
  84126. set: function (value) {
  84127. this._isEnabled = value;
  84128. },
  84129. enumerable: true,
  84130. configurable: true
  84131. });
  84132. LensFlareSystem.prototype.getScene = function () {
  84133. return this._scene;
  84134. };
  84135. LensFlareSystem.prototype.getEmitter = function () {
  84136. return this._emitter;
  84137. };
  84138. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84139. this._emitter = newEmitter;
  84140. };
  84141. LensFlareSystem.prototype.getEmitterPosition = function () {
  84142. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84143. };
  84144. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84145. var position = this.getEmitterPosition();
  84146. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84147. this._positionX = position.x;
  84148. this._positionY = position.y;
  84149. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84150. if (this.viewportBorder > 0) {
  84151. globalViewport.x -= this.viewportBorder;
  84152. globalViewport.y -= this.viewportBorder;
  84153. globalViewport.width += this.viewportBorder * 2;
  84154. globalViewport.height += this.viewportBorder * 2;
  84155. position.x += this.viewportBorder;
  84156. position.y += this.viewportBorder;
  84157. this._positionX += this.viewportBorder;
  84158. this._positionY += this.viewportBorder;
  84159. }
  84160. if (position.z > 0) {
  84161. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84162. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84163. return true;
  84164. }
  84165. return true;
  84166. }
  84167. return false;
  84168. };
  84169. LensFlareSystem.prototype._isVisible = function () {
  84170. if (!this._isEnabled || !this._scene.activeCamera) {
  84171. return false;
  84172. }
  84173. var emitterPosition = this.getEmitterPosition();
  84174. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84175. var distance = direction.length();
  84176. direction.normalize();
  84177. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84178. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84179. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84180. };
  84181. LensFlareSystem.prototype.render = function () {
  84182. if (!this._effect.isReady() || !this._scene.activeCamera)
  84183. return false;
  84184. var engine = this._scene.getEngine();
  84185. var viewport = this._scene.activeCamera.viewport;
  84186. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84187. // Position
  84188. if (!this.computeEffectivePosition(globalViewport)) {
  84189. return false;
  84190. }
  84191. // Visibility
  84192. if (!this._isVisible()) {
  84193. return false;
  84194. }
  84195. // Intensity
  84196. var awayX;
  84197. var awayY;
  84198. if (this._positionX < this.borderLimit + globalViewport.x) {
  84199. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84200. }
  84201. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84202. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84203. }
  84204. else {
  84205. awayX = 0;
  84206. }
  84207. if (this._positionY < this.borderLimit + globalViewport.y) {
  84208. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84209. }
  84210. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84211. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84212. }
  84213. else {
  84214. awayY = 0;
  84215. }
  84216. var away = (awayX > awayY) ? awayX : awayY;
  84217. away -= this.viewportBorder;
  84218. if (away > this.borderLimit) {
  84219. away = this.borderLimit;
  84220. }
  84221. var intensity = 1.0 - (away / this.borderLimit);
  84222. if (intensity < 0) {
  84223. return false;
  84224. }
  84225. if (intensity > 1.0) {
  84226. intensity = 1.0;
  84227. }
  84228. if (this.viewportBorder > 0) {
  84229. globalViewport.x += this.viewportBorder;
  84230. globalViewport.y += this.viewportBorder;
  84231. globalViewport.width -= this.viewportBorder * 2;
  84232. globalViewport.height -= this.viewportBorder * 2;
  84233. this._positionX -= this.viewportBorder;
  84234. this._positionY -= this.viewportBorder;
  84235. }
  84236. // Position
  84237. var centerX = globalViewport.x + globalViewport.width / 2;
  84238. var centerY = globalViewport.y + globalViewport.height / 2;
  84239. var distX = centerX - this._positionX;
  84240. var distY = centerY - this._positionY;
  84241. // Effects
  84242. engine.enableEffect(this._effect);
  84243. engine.setState(false);
  84244. engine.setDepthBuffer(false);
  84245. // VBOs
  84246. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84247. // Flares
  84248. for (var index = 0; index < this.lensFlares.length; index++) {
  84249. var flare = this.lensFlares[index];
  84250. engine.setAlphaMode(flare.alphaMode);
  84251. var x = centerX - (distX * flare.position);
  84252. var y = centerY - (distY * flare.position);
  84253. var cw = flare.size;
  84254. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84255. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84256. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84257. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84258. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84259. // Texture
  84260. this._effect.setTexture("textureSampler", flare.texture);
  84261. // Color
  84262. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84263. // Draw order
  84264. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84265. }
  84266. engine.setDepthBuffer(true);
  84267. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84268. return true;
  84269. };
  84270. LensFlareSystem.prototype.dispose = function () {
  84271. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84272. if (vertexBuffer) {
  84273. vertexBuffer.dispose();
  84274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84275. }
  84276. if (this._indexBuffer) {
  84277. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84278. this._indexBuffer = null;
  84279. }
  84280. while (this.lensFlares.length) {
  84281. this.lensFlares[0].dispose();
  84282. }
  84283. // Remove from scene
  84284. var index = this._scene.lensFlareSystems.indexOf(this);
  84285. this._scene.lensFlareSystems.splice(index, 1);
  84286. };
  84287. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84288. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84289. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84290. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84291. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84292. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84293. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84294. var parsedFlare = parsedLensFlareSystem.flares[index];
  84295. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84296. }
  84297. return lensFlareSystem;
  84298. };
  84299. LensFlareSystem.prototype.serialize = function () {
  84300. var serializationObject = {};
  84301. serializationObject.id = this.id;
  84302. serializationObject.name = this.name;
  84303. serializationObject.emitterId = this.getEmitter().id;
  84304. serializationObject.borderLimit = this.borderLimit;
  84305. serializationObject.flares = [];
  84306. for (var index = 0; index < this.lensFlares.length; index++) {
  84307. var flare = this.lensFlares[index];
  84308. serializationObject.flares.push({
  84309. size: flare.size,
  84310. position: flare.position,
  84311. color: flare.color.asArray(),
  84312. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84313. });
  84314. }
  84315. return serializationObject;
  84316. };
  84317. return LensFlareSystem;
  84318. }());
  84319. BABYLON.LensFlareSystem = LensFlareSystem;
  84320. })(BABYLON || (BABYLON = {}));
  84321. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84322. var BABYLON;
  84323. (function (BABYLON) {
  84324. /**
  84325. * This is a holder class for the physics joint created by the physics plugin.
  84326. * It holds a set of functions to control the underlying joint.
  84327. */
  84328. var PhysicsJoint = /** @class */ (function () {
  84329. function PhysicsJoint(type, jointData) {
  84330. this.type = type;
  84331. this.jointData = jointData;
  84332. jointData.nativeParams = jointData.nativeParams || {};
  84333. }
  84334. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84335. get: function () {
  84336. return this._physicsJoint;
  84337. },
  84338. set: function (newJoint) {
  84339. if (this._physicsJoint) {
  84340. //remove from the wolrd
  84341. }
  84342. this._physicsJoint = newJoint;
  84343. },
  84344. enumerable: true,
  84345. configurable: true
  84346. });
  84347. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84348. set: function (physicsPlugin) {
  84349. this._physicsPlugin = physicsPlugin;
  84350. },
  84351. enumerable: true,
  84352. configurable: true
  84353. });
  84354. /**
  84355. * Execute a function that is physics-plugin specific.
  84356. * @param {Function} func the function that will be executed.
  84357. * It accepts two parameters: the physics world and the physics joint.
  84358. */
  84359. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84360. func(this._physicsPlugin.world, this._physicsJoint);
  84361. };
  84362. //TODO check if the native joints are the same
  84363. //Joint Types
  84364. PhysicsJoint.DistanceJoint = 0;
  84365. PhysicsJoint.HingeJoint = 1;
  84366. PhysicsJoint.BallAndSocketJoint = 2;
  84367. PhysicsJoint.WheelJoint = 3;
  84368. PhysicsJoint.SliderJoint = 4;
  84369. //OIMO
  84370. PhysicsJoint.PrismaticJoint = 5;
  84371. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84372. PhysicsJoint.UniversalJoint = 6;
  84373. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84374. //Cannon
  84375. //Similar to a Ball-Joint. Different in params
  84376. PhysicsJoint.PointToPointJoint = 8;
  84377. //Cannon only at the moment
  84378. PhysicsJoint.SpringJoint = 9;
  84379. PhysicsJoint.LockJoint = 10;
  84380. return PhysicsJoint;
  84381. }());
  84382. BABYLON.PhysicsJoint = PhysicsJoint;
  84383. /**
  84384. * A class representing a physics distance joint.
  84385. */
  84386. var DistanceJoint = /** @class */ (function (_super) {
  84387. __extends(DistanceJoint, _super);
  84388. function DistanceJoint(jointData) {
  84389. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84390. }
  84391. /**
  84392. * Update the predefined distance.
  84393. */
  84394. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84395. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84396. };
  84397. return DistanceJoint;
  84398. }(PhysicsJoint));
  84399. BABYLON.DistanceJoint = DistanceJoint;
  84400. var MotorEnabledJoint = /** @class */ (function (_super) {
  84401. __extends(MotorEnabledJoint, _super);
  84402. function MotorEnabledJoint(type, jointData) {
  84403. return _super.call(this, type, jointData) || this;
  84404. }
  84405. /**
  84406. * Set the motor values.
  84407. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84408. * @param {number} force the force to apply
  84409. * @param {number} maxForce max force for this motor.
  84410. */
  84411. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84412. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84413. };
  84414. /**
  84415. * Set the motor's limits.
  84416. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84417. */
  84418. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84419. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84420. };
  84421. return MotorEnabledJoint;
  84422. }(PhysicsJoint));
  84423. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84424. /**
  84425. * This class represents a single hinge physics joint
  84426. */
  84427. var HingeJoint = /** @class */ (function (_super) {
  84428. __extends(HingeJoint, _super);
  84429. function HingeJoint(jointData) {
  84430. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84431. }
  84432. /**
  84433. * Set the motor values.
  84434. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84435. * @param {number} force the force to apply
  84436. * @param {number} maxForce max force for this motor.
  84437. */
  84438. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84439. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84440. };
  84441. /**
  84442. * Set the motor's limits.
  84443. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84444. */
  84445. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84446. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84447. };
  84448. return HingeJoint;
  84449. }(MotorEnabledJoint));
  84450. BABYLON.HingeJoint = HingeJoint;
  84451. /**
  84452. * This class represents a dual hinge physics joint (same as wheel joint)
  84453. */
  84454. var Hinge2Joint = /** @class */ (function (_super) {
  84455. __extends(Hinge2Joint, _super);
  84456. function Hinge2Joint(jointData) {
  84457. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84458. }
  84459. /**
  84460. * Set the motor values.
  84461. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84462. * @param {number} force the force to apply
  84463. * @param {number} maxForce max force for this motor.
  84464. * @param {motorIndex} the motor's index, 0 or 1.
  84465. */
  84466. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84467. if (motorIndex === void 0) { motorIndex = 0; }
  84468. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84469. };
  84470. /**
  84471. * Set the motor limits.
  84472. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84473. * @param {number} upperLimit the upper limit
  84474. * @param {number} lowerLimit lower limit
  84475. * @param {motorIndex} the motor's index, 0 or 1.
  84476. */
  84477. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84478. if (motorIndex === void 0) { motorIndex = 0; }
  84479. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84480. };
  84481. return Hinge2Joint;
  84482. }(MotorEnabledJoint));
  84483. BABYLON.Hinge2Joint = Hinge2Joint;
  84484. })(BABYLON || (BABYLON = {}));
  84485. //# sourceMappingURL=babylon.physicsJoint.js.map
  84486. var BABYLON;
  84487. (function (BABYLON) {
  84488. var PhysicsImpostor = /** @class */ (function () {
  84489. function PhysicsImpostor(object, type, _options, _scene) {
  84490. if (_options === void 0) { _options = { mass: 0 }; }
  84491. var _this = this;
  84492. this.object = object;
  84493. this.type = type;
  84494. this._options = _options;
  84495. this._scene = _scene;
  84496. this._bodyUpdateRequired = false;
  84497. this._onBeforePhysicsStepCallbacks = new Array();
  84498. this._onAfterPhysicsStepCallbacks = new Array();
  84499. this._onPhysicsCollideCallbacks = [];
  84500. this._deltaPosition = BABYLON.Vector3.Zero();
  84501. this._isDisposed = false;
  84502. //temp variables for parent rotation calculations
  84503. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84504. this._tmpQuat = new BABYLON.Quaternion();
  84505. this._tmpQuat2 = new BABYLON.Quaternion();
  84506. /**
  84507. * this function is executed by the physics engine.
  84508. */
  84509. this.beforeStep = function () {
  84510. if (!_this._physicsEngine) {
  84511. return;
  84512. }
  84513. _this.object.translate(_this._deltaPosition, -1);
  84514. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84515. _this.object.computeWorldMatrix(false);
  84516. if (_this.object.parent && _this.object.rotationQuaternion) {
  84517. _this.getParentsRotation();
  84518. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84519. }
  84520. else {
  84521. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84522. }
  84523. if (!_this._options.disableBidirectionalTransformation) {
  84524. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84525. }
  84526. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84527. func(_this);
  84528. });
  84529. };
  84530. /**
  84531. * this function is executed by the physics engine.
  84532. */
  84533. this.afterStep = function () {
  84534. if (!_this._physicsEngine) {
  84535. return;
  84536. }
  84537. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84538. func(_this);
  84539. });
  84540. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84541. // object has now its world rotation. needs to be converted to local.
  84542. if (_this.object.parent && _this.object.rotationQuaternion) {
  84543. _this.getParentsRotation();
  84544. _this._tmpQuat.conjugateInPlace();
  84545. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84546. }
  84547. // take the position set and make it the absolute position of this object.
  84548. _this.object.setAbsolutePosition(_this.object.position);
  84549. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84550. _this.object.translate(_this._deltaPosition, 1);
  84551. };
  84552. /**
  84553. * Legacy collision detection event support
  84554. */
  84555. this.onCollideEvent = null;
  84556. //event and body object due to cannon's event-based architecture.
  84557. this.onCollide = function (e) {
  84558. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84559. return;
  84560. }
  84561. if (!_this._physicsEngine) {
  84562. return;
  84563. }
  84564. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84565. if (otherImpostor) {
  84566. // Legacy collision detection event support
  84567. if (_this.onCollideEvent) {
  84568. _this.onCollideEvent(_this, otherImpostor);
  84569. }
  84570. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84571. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84572. }).forEach(function (obj) {
  84573. obj.callback(_this, otherImpostor);
  84574. });
  84575. }
  84576. };
  84577. //sanity check!
  84578. if (!this.object) {
  84579. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84580. return;
  84581. }
  84582. //legacy support for old syntax.
  84583. if (!this._scene && object.getScene) {
  84584. this._scene = object.getScene();
  84585. }
  84586. if (!this._scene) {
  84587. return;
  84588. }
  84589. this._physicsEngine = this._scene.getPhysicsEngine();
  84590. if (!this._physicsEngine) {
  84591. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84592. }
  84593. else {
  84594. //set the object's quaternion, if not set
  84595. if (!this.object.rotationQuaternion) {
  84596. if (this.object.rotation) {
  84597. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84598. }
  84599. else {
  84600. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84601. }
  84602. }
  84603. //default options params
  84604. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84605. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84606. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84607. this._joints = [];
  84608. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84609. if (!this.object.parent || this._options.ignoreParent) {
  84610. this._init();
  84611. }
  84612. else if (this.object.parent.physicsImpostor) {
  84613. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84614. }
  84615. }
  84616. }
  84617. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84618. get: function () {
  84619. return this._isDisposed;
  84620. },
  84621. enumerable: true,
  84622. configurable: true
  84623. });
  84624. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84625. get: function () {
  84626. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84627. },
  84628. set: function (value) {
  84629. this.setMass(value);
  84630. },
  84631. enumerable: true,
  84632. configurable: true
  84633. });
  84634. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84635. get: function () {
  84636. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84637. },
  84638. set: function (value) {
  84639. if (!this._physicsEngine) {
  84640. return;
  84641. }
  84642. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84643. },
  84644. enumerable: true,
  84645. configurable: true
  84646. });
  84647. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84648. get: function () {
  84649. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84650. },
  84651. set: function (value) {
  84652. if (!this._physicsEngine) {
  84653. return;
  84654. }
  84655. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84656. },
  84657. enumerable: true,
  84658. configurable: true
  84659. });
  84660. /**
  84661. * This function will completly initialize this impostor.
  84662. * It will create a new body - but only if this mesh has no parent.
  84663. * If it has, this impostor will not be used other than to define the impostor
  84664. * of the child mesh.
  84665. */
  84666. PhysicsImpostor.prototype._init = function () {
  84667. if (!this._physicsEngine) {
  84668. return;
  84669. }
  84670. this._physicsEngine.removeImpostor(this);
  84671. this.physicsBody = null;
  84672. this._parent = this._parent || this._getPhysicsParent();
  84673. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84674. this._physicsEngine.addImpostor(this);
  84675. }
  84676. };
  84677. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84678. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84679. var parentMesh = this.object.parent;
  84680. return parentMesh.physicsImpostor;
  84681. }
  84682. return null;
  84683. };
  84684. /**
  84685. * Should a new body be generated.
  84686. */
  84687. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84688. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84689. };
  84690. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84691. this.forceUpdate();
  84692. };
  84693. /**
  84694. * Force a regeneration of this or the parent's impostor's body.
  84695. * Use under cautious - This will remove all joints already implemented.
  84696. */
  84697. PhysicsImpostor.prototype.forceUpdate = function () {
  84698. this._init();
  84699. if (this.parent && !this._options.ignoreParent) {
  84700. this.parent.forceUpdate();
  84701. }
  84702. };
  84703. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84704. /*public get mesh(): AbstractMesh {
  84705. return this._mesh;
  84706. }*/
  84707. /**
  84708. * Gets the body that holds this impostor. Either its own, or its parent.
  84709. */
  84710. get: function () {
  84711. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84712. },
  84713. /**
  84714. * Set the physics body. Used mainly by the physics engine/plugin
  84715. */
  84716. set: function (physicsBody) {
  84717. if (this._physicsBody && this._physicsEngine) {
  84718. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84719. }
  84720. this._physicsBody = physicsBody;
  84721. this.resetUpdateFlags();
  84722. },
  84723. enumerable: true,
  84724. configurable: true
  84725. });
  84726. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84727. get: function () {
  84728. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84729. },
  84730. set: function (value) {
  84731. this._parent = value;
  84732. },
  84733. enumerable: true,
  84734. configurable: true
  84735. });
  84736. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84737. this._bodyUpdateRequired = false;
  84738. };
  84739. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84740. if (this.object.getBoundingInfo) {
  84741. var q = this.object.rotationQuaternion;
  84742. //reset rotation
  84743. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84744. //calculate the world matrix with no rotation
  84745. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84746. var boundingInfo = this.object.getBoundingInfo();
  84747. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84748. //bring back the rotation
  84749. this.object.rotationQuaternion = q;
  84750. //calculate the world matrix with the new rotation
  84751. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84752. return size;
  84753. }
  84754. else {
  84755. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84756. }
  84757. };
  84758. PhysicsImpostor.prototype.getObjectCenter = function () {
  84759. if (this.object.getBoundingInfo) {
  84760. var boundingInfo = this.object.getBoundingInfo();
  84761. return boundingInfo.boundingBox.centerWorld;
  84762. }
  84763. else {
  84764. return this.object.position;
  84765. }
  84766. };
  84767. /**
  84768. * Get a specific parametes from the options parameter.
  84769. */
  84770. PhysicsImpostor.prototype.getParam = function (paramName) {
  84771. return this._options[paramName];
  84772. };
  84773. /**
  84774. * Sets a specific parameter in the options given to the physics plugin
  84775. */
  84776. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84777. this._options[paramName] = value;
  84778. this._bodyUpdateRequired = true;
  84779. };
  84780. /**
  84781. * Specifically change the body's mass option. Won't recreate the physics body object
  84782. */
  84783. PhysicsImpostor.prototype.setMass = function (mass) {
  84784. if (this.getParam("mass") !== mass) {
  84785. this.setParam("mass", mass);
  84786. }
  84787. if (this._physicsEngine) {
  84788. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84789. }
  84790. };
  84791. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84792. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84793. };
  84794. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84795. if (this._physicsEngine) {
  84796. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84797. }
  84798. };
  84799. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84800. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84801. };
  84802. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84803. if (this._physicsEngine) {
  84804. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84805. }
  84806. };
  84807. /**
  84808. * Execute a function with the physics plugin native code.
  84809. * Provide a function the will have two variables - the world object and the physics body object.
  84810. */
  84811. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84812. if (this._physicsEngine) {
  84813. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84814. }
  84815. };
  84816. /**
  84817. * Register a function that will be executed before the physics world is stepping forward.
  84818. */
  84819. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84820. this._onBeforePhysicsStepCallbacks.push(func);
  84821. };
  84822. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84823. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84824. if (index > -1) {
  84825. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84826. }
  84827. else {
  84828. BABYLON.Tools.Warn("Function to remove was not found");
  84829. }
  84830. };
  84831. /**
  84832. * Register a function that will be executed after the physics step
  84833. */
  84834. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84835. this._onAfterPhysicsStepCallbacks.push(func);
  84836. };
  84837. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84838. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84839. if (index > -1) {
  84840. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84841. }
  84842. else {
  84843. BABYLON.Tools.Warn("Function to remove was not found");
  84844. }
  84845. };
  84846. /**
  84847. * register a function that will be executed when this impostor collides against a different body.
  84848. */
  84849. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84850. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84851. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84852. };
  84853. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84854. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84855. var index = -1;
  84856. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84857. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84858. // chcek the arrays match
  84859. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84860. return collidedAgainstList.indexOf(impostor) > -1;
  84861. });
  84862. if (sameList) {
  84863. index = idx;
  84864. }
  84865. return sameList;
  84866. }
  84867. return false;
  84868. });
  84869. if (found) {
  84870. this._onPhysicsCollideCallbacks.splice(index, 1);
  84871. }
  84872. else {
  84873. BABYLON.Tools.Warn("Function to remove was not found");
  84874. }
  84875. };
  84876. PhysicsImpostor.prototype.getParentsRotation = function () {
  84877. var parent = this.object.parent;
  84878. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84879. while (parent) {
  84880. if (parent.rotationQuaternion) {
  84881. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84882. }
  84883. else {
  84884. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84885. }
  84886. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84887. parent = parent.parent;
  84888. }
  84889. return this._tmpQuat;
  84890. };
  84891. /**
  84892. * Apply a force
  84893. */
  84894. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84895. if (this._physicsEngine) {
  84896. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84897. }
  84898. return this;
  84899. };
  84900. /**
  84901. * Apply an impulse
  84902. */
  84903. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84904. if (this._physicsEngine) {
  84905. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84906. }
  84907. return this;
  84908. };
  84909. /**
  84910. * A help function to create a joint.
  84911. */
  84912. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84913. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84914. this.addJoint(otherImpostor, joint);
  84915. return this;
  84916. };
  84917. /**
  84918. * Add a joint to this impostor with a different impostor.
  84919. */
  84920. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84921. this._joints.push({
  84922. otherImpostor: otherImpostor,
  84923. joint: joint
  84924. });
  84925. if (this._physicsEngine) {
  84926. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84927. }
  84928. return this;
  84929. };
  84930. /**
  84931. * Will keep this body still, in a sleep mode.
  84932. */
  84933. PhysicsImpostor.prototype.sleep = function () {
  84934. if (this._physicsEngine) {
  84935. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84936. }
  84937. return this;
  84938. };
  84939. /**
  84940. * Wake the body up.
  84941. */
  84942. PhysicsImpostor.prototype.wakeUp = function () {
  84943. if (this._physicsEngine) {
  84944. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84945. }
  84946. return this;
  84947. };
  84948. PhysicsImpostor.prototype.clone = function (newObject) {
  84949. if (!newObject)
  84950. return null;
  84951. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84952. };
  84953. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84954. var _this = this;
  84955. //no dispose if no physics engine is available.
  84956. if (!this._physicsEngine) {
  84957. return;
  84958. }
  84959. this._joints.forEach(function (j) {
  84960. if (_this._physicsEngine) {
  84961. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84962. }
  84963. });
  84964. //dispose the physics body
  84965. this._physicsEngine.removeImpostor(this);
  84966. if (this.parent) {
  84967. this.parent.forceUpdate();
  84968. }
  84969. else {
  84970. /*this._object.getChildMeshes().forEach(function(mesh) {
  84971. if (mesh.physicsImpostor) {
  84972. if (disposeChildren) {
  84973. mesh.physicsImpostor.dispose();
  84974. mesh.physicsImpostor = null;
  84975. }
  84976. }
  84977. })*/
  84978. }
  84979. this._isDisposed = true;
  84980. };
  84981. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84982. this._deltaPosition.copyFrom(position);
  84983. };
  84984. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84985. if (!this._deltaRotation) {
  84986. this._deltaRotation = new BABYLON.Quaternion();
  84987. }
  84988. this._deltaRotation.copyFrom(rotation);
  84989. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84990. };
  84991. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84992. if (this._physicsEngine) {
  84993. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84994. }
  84995. return this;
  84996. };
  84997. PhysicsImpostor.prototype.getRadius = function () {
  84998. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84999. };
  85000. /**
  85001. * Sync a bone with this impostor
  85002. * @param bone The bone to sync to the impostor.
  85003. * @param boneMesh The mesh that the bone is influencing.
  85004. * @param jointPivot The pivot of the joint / bone in local space.
  85005. * @param distToJoint Optional distance from the impostor to the joint.
  85006. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85007. */
  85008. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85009. var tempVec = PhysicsImpostor._tmpVecs[0];
  85010. var mesh = this.object;
  85011. if (mesh.rotationQuaternion) {
  85012. if (adjustRotation) {
  85013. var tempQuat = PhysicsImpostor._tmpQuat;
  85014. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85015. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85016. }
  85017. else {
  85018. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85019. }
  85020. }
  85021. tempVec.x = 0;
  85022. tempVec.y = 0;
  85023. tempVec.z = 0;
  85024. if (jointPivot) {
  85025. tempVec.x = jointPivot.x;
  85026. tempVec.y = jointPivot.y;
  85027. tempVec.z = jointPivot.z;
  85028. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85029. if (distToJoint === undefined || distToJoint === null) {
  85030. distToJoint = jointPivot.length();
  85031. }
  85032. tempVec.x *= distToJoint;
  85033. tempVec.y *= distToJoint;
  85034. tempVec.z *= distToJoint;
  85035. }
  85036. if (bone.getParent()) {
  85037. tempVec.addInPlace(mesh.getAbsolutePosition());
  85038. bone.setAbsolutePosition(tempVec, boneMesh);
  85039. }
  85040. else {
  85041. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85042. boneMesh.position.x -= tempVec.x;
  85043. boneMesh.position.y -= tempVec.y;
  85044. boneMesh.position.z -= tempVec.z;
  85045. }
  85046. };
  85047. /**
  85048. * Sync impostor to a bone
  85049. * @param bone The bone that the impostor will be synced to.
  85050. * @param boneMesh The mesh that the bone is influencing.
  85051. * @param jointPivot The pivot of the joint / bone in local space.
  85052. * @param distToJoint Optional distance from the impostor to the joint.
  85053. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85054. * @param boneAxis Optional vector3 axis the bone is aligned with
  85055. */
  85056. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85057. var mesh = this.object;
  85058. if (mesh.rotationQuaternion) {
  85059. if (adjustRotation) {
  85060. var tempQuat = PhysicsImpostor._tmpQuat;
  85061. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85062. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85063. }
  85064. else {
  85065. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85066. }
  85067. }
  85068. var pos = PhysicsImpostor._tmpVecs[0];
  85069. var boneDir = PhysicsImpostor._tmpVecs[1];
  85070. if (!boneAxis) {
  85071. boneAxis = PhysicsImpostor._tmpVecs[2];
  85072. boneAxis.x = 0;
  85073. boneAxis.y = 1;
  85074. boneAxis.z = 0;
  85075. }
  85076. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85077. bone.getAbsolutePositionToRef(boneMesh, pos);
  85078. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85079. distToJoint = jointPivot.length();
  85080. }
  85081. if (distToJoint !== undefined && distToJoint !== null) {
  85082. pos.x += boneDir.x * distToJoint;
  85083. pos.y += boneDir.y * distToJoint;
  85084. pos.z += boneDir.z * distToJoint;
  85085. }
  85086. mesh.setAbsolutePosition(pos);
  85087. };
  85088. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85089. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85090. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85091. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85092. //Impostor types
  85093. PhysicsImpostor.NoImpostor = 0;
  85094. PhysicsImpostor.SphereImpostor = 1;
  85095. PhysicsImpostor.BoxImpostor = 2;
  85096. PhysicsImpostor.PlaneImpostor = 3;
  85097. PhysicsImpostor.MeshImpostor = 4;
  85098. PhysicsImpostor.CylinderImpostor = 7;
  85099. PhysicsImpostor.ParticleImpostor = 8;
  85100. PhysicsImpostor.HeightmapImpostor = 9;
  85101. return PhysicsImpostor;
  85102. }());
  85103. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85104. })(BABYLON || (BABYLON = {}));
  85105. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85106. var BABYLON;
  85107. (function (BABYLON) {
  85108. var PhysicsEngine = /** @class */ (function () {
  85109. function PhysicsEngine(gravity, _physicsPlugin) {
  85110. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85111. this._physicsPlugin = _physicsPlugin;
  85112. //new methods and parameters
  85113. this._impostors = [];
  85114. this._joints = [];
  85115. if (!this._physicsPlugin.isSupported()) {
  85116. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85117. + "Please make sure it is included.");
  85118. }
  85119. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85120. this.setGravity(gravity);
  85121. this.setTimeStep();
  85122. }
  85123. PhysicsEngine.prototype.setGravity = function (gravity) {
  85124. this.gravity = gravity;
  85125. this._physicsPlugin.setGravity(this.gravity);
  85126. };
  85127. /**
  85128. * Set the time step of the physics engine.
  85129. * default is 1/60.
  85130. * To slow it down, enter 1/600 for example.
  85131. * To speed it up, 1/30
  85132. * @param {number} newTimeStep the new timestep to apply to this world.
  85133. */
  85134. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85135. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85136. this._physicsPlugin.setTimeStep(newTimeStep);
  85137. };
  85138. /**
  85139. * Get the time step of the physics engine.
  85140. */
  85141. PhysicsEngine.prototype.getTimeStep = function () {
  85142. return this._physicsPlugin.getTimeStep();
  85143. };
  85144. PhysicsEngine.prototype.dispose = function () {
  85145. this._impostors.forEach(function (impostor) {
  85146. impostor.dispose();
  85147. });
  85148. this._physicsPlugin.dispose();
  85149. };
  85150. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85151. return this._physicsPlugin.name;
  85152. };
  85153. /**
  85154. * Adding a new impostor for the impostor tracking.
  85155. * This will be done by the impostor itself.
  85156. * @param {PhysicsImpostor} impostor the impostor to add
  85157. */
  85158. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85159. impostor.uniqueId = this._impostors.push(impostor);
  85160. //if no parent, generate the body
  85161. if (!impostor.parent) {
  85162. this._physicsPlugin.generatePhysicsBody(impostor);
  85163. }
  85164. };
  85165. /**
  85166. * Remove an impostor from the engine.
  85167. * This impostor and its mesh will not longer be updated by the physics engine.
  85168. * @param {PhysicsImpostor} impostor the impostor to remove
  85169. */
  85170. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85171. var index = this._impostors.indexOf(impostor);
  85172. if (index > -1) {
  85173. var removed = this._impostors.splice(index, 1);
  85174. //Is it needed?
  85175. if (removed.length) {
  85176. //this will also remove it from the world.
  85177. removed[0].physicsBody = null;
  85178. }
  85179. }
  85180. };
  85181. /**
  85182. * Add a joint to the physics engine
  85183. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85184. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85185. * @param {PhysicsJoint} the joint that will connect both impostors.
  85186. */
  85187. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85188. var impostorJoint = {
  85189. mainImpostor: mainImpostor,
  85190. connectedImpostor: connectedImpostor,
  85191. joint: joint
  85192. };
  85193. joint.physicsPlugin = this._physicsPlugin;
  85194. this._joints.push(impostorJoint);
  85195. this._physicsPlugin.generateJoint(impostorJoint);
  85196. };
  85197. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85198. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85199. return (impostorJoint.connectedImpostor === connectedImpostor
  85200. && impostorJoint.joint === joint
  85201. && impostorJoint.mainImpostor === mainImpostor);
  85202. });
  85203. if (matchingJoints.length) {
  85204. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85205. //TODO remove it from the list as well
  85206. }
  85207. };
  85208. /**
  85209. * Called by the scene. no need to call it.
  85210. */
  85211. PhysicsEngine.prototype._step = function (delta) {
  85212. var _this = this;
  85213. //check if any mesh has no body / requires an update
  85214. this._impostors.forEach(function (impostor) {
  85215. if (impostor.isBodyInitRequired()) {
  85216. _this._physicsPlugin.generatePhysicsBody(impostor);
  85217. }
  85218. });
  85219. if (delta > 0.1) {
  85220. delta = 0.1;
  85221. }
  85222. else if (delta <= 0) {
  85223. delta = 1.0 / 60.0;
  85224. }
  85225. this._physicsPlugin.executeStep(delta, this._impostors);
  85226. };
  85227. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85228. return this._physicsPlugin;
  85229. };
  85230. PhysicsEngine.prototype.getImpostors = function () {
  85231. return this._impostors;
  85232. };
  85233. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85234. for (var i = 0; i < this._impostors.length; ++i) {
  85235. if (this._impostors[i].object === object) {
  85236. return this._impostors[i];
  85237. }
  85238. }
  85239. return null;
  85240. };
  85241. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85242. for (var i = 0; i < this._impostors.length; ++i) {
  85243. if (this._impostors[i].physicsBody === body) {
  85244. return this._impostors[i];
  85245. }
  85246. }
  85247. return null;
  85248. };
  85249. // Statics
  85250. PhysicsEngine.Epsilon = 0.001;
  85251. return PhysicsEngine;
  85252. }());
  85253. BABYLON.PhysicsEngine = PhysicsEngine;
  85254. })(BABYLON || (BABYLON = {}));
  85255. //# sourceMappingURL=babylon.physicsEngine.js.map
  85256. var BABYLON;
  85257. (function (BABYLON) {
  85258. var PhysicsHelper = /** @class */ (function () {
  85259. function PhysicsHelper(scene) {
  85260. this._scene = scene;
  85261. this._physicsEngine = this._scene.getPhysicsEngine();
  85262. if (!this._physicsEngine) {
  85263. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85264. }
  85265. }
  85266. /**
  85267. * @param {Vector3} origin the origin of the explosion
  85268. * @param {number} radius the explosion radius
  85269. * @param {number} strength the explosion strength
  85270. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85271. */
  85272. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85273. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85274. if (!this._physicsEngine) {
  85275. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85276. return null;
  85277. }
  85278. var impostors = this._physicsEngine.getImpostors();
  85279. if (impostors.length === 0) {
  85280. return null;
  85281. }
  85282. var event = new PhysicsRadialExplosionEvent(this._scene);
  85283. impostors.forEach(function (impostor) {
  85284. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85285. if (!impostorForceAndContactPoint) {
  85286. return;
  85287. }
  85288. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85289. });
  85290. event.dispose(false);
  85291. return event;
  85292. };
  85293. /**
  85294. * @param {Vector3} origin the origin of the explosion
  85295. * @param {number} radius the explosion radius
  85296. * @param {number} strength the explosion strength
  85297. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85298. */
  85299. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85300. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85301. if (!this._physicsEngine) {
  85302. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85303. return null;
  85304. }
  85305. var impostors = this._physicsEngine.getImpostors();
  85306. if (impostors.length === 0) {
  85307. return null;
  85308. }
  85309. var event = new PhysicsRadialExplosionEvent(this._scene);
  85310. impostors.forEach(function (impostor) {
  85311. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85312. if (!impostorForceAndContactPoint) {
  85313. return;
  85314. }
  85315. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85316. });
  85317. event.dispose(false);
  85318. return event;
  85319. };
  85320. /**
  85321. * @param {Vector3} origin the origin of the explosion
  85322. * @param {number} radius the explosion radius
  85323. * @param {number} strength the explosion strength
  85324. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85325. */
  85326. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85327. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85328. if (!this._physicsEngine) {
  85329. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85330. return null;
  85331. }
  85332. var impostors = this._physicsEngine.getImpostors();
  85333. if (impostors.length === 0) {
  85334. return null;
  85335. }
  85336. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85337. event.dispose(false);
  85338. return event;
  85339. };
  85340. /**
  85341. * @param {Vector3} origin the origin of the updraft
  85342. * @param {number} radius the radius of the updraft
  85343. * @param {number} strength the strength of the updraft
  85344. * @param {number} height the height of the updraft
  85345. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85346. */
  85347. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85348. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85349. if (!this._physicsEngine) {
  85350. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85351. return null;
  85352. }
  85353. if (this._physicsEngine.getImpostors().length === 0) {
  85354. return null;
  85355. }
  85356. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85357. event.dispose(false);
  85358. return event;
  85359. };
  85360. /**
  85361. * @param {Vector3} origin the of the vortex
  85362. * @param {number} radius the radius of the vortex
  85363. * @param {number} strength the strength of the vortex
  85364. * @param {number} height the height of the vortex
  85365. */
  85366. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85367. if (!this._physicsEngine) {
  85368. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85369. return null;
  85370. }
  85371. if (this._physicsEngine.getImpostors().length === 0) {
  85372. return null;
  85373. }
  85374. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85375. event.dispose(false);
  85376. return event;
  85377. };
  85378. return PhysicsHelper;
  85379. }());
  85380. BABYLON.PhysicsHelper = PhysicsHelper;
  85381. /***** Radial explosion *****/
  85382. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85383. function PhysicsRadialExplosionEvent(scene) {
  85384. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85385. this._rays = [];
  85386. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85387. this._scene = scene;
  85388. }
  85389. /**
  85390. * Returns the data related to the radial explosion event (sphere & rays).
  85391. * @returns {PhysicsRadialExplosionEventData}
  85392. */
  85393. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85394. this._dataFetched = true;
  85395. return {
  85396. sphere: this._sphere,
  85397. rays: this._rays,
  85398. };
  85399. };
  85400. /**
  85401. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85402. * @param impostor
  85403. * @param {Vector3} origin the origin of the explosion
  85404. * @param {number} radius the explosion radius
  85405. * @param {number} strength the explosion strength
  85406. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85407. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85408. */
  85409. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85410. if (impostor.mass === 0) {
  85411. return null;
  85412. }
  85413. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85414. return null;
  85415. }
  85416. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85417. return null;
  85418. }
  85419. var impostorObjectCenter = impostor.getObjectCenter();
  85420. var direction = impostorObjectCenter.subtract(origin);
  85421. var ray = new BABYLON.Ray(origin, direction, radius);
  85422. this._rays.push(ray);
  85423. var hit = ray.intersectsMesh(impostor.object);
  85424. var contactPoint = hit.pickedPoint;
  85425. if (!contactPoint) {
  85426. return null;
  85427. }
  85428. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85429. if (distanceFromOrigin > radius) {
  85430. return null;
  85431. }
  85432. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85433. ? strength
  85434. : strength * (1 - (distanceFromOrigin / radius));
  85435. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85436. return { force: force, contactPoint: contactPoint };
  85437. };
  85438. /**
  85439. * Disposes the sphere.
  85440. * @param {bolean} force
  85441. */
  85442. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85443. var _this = this;
  85444. if (force === void 0) { force = true; }
  85445. if (force) {
  85446. this._sphere.dispose();
  85447. }
  85448. else {
  85449. setTimeout(function () {
  85450. if (!_this._dataFetched) {
  85451. _this._sphere.dispose();
  85452. }
  85453. }, 0);
  85454. }
  85455. };
  85456. /*** Helpers ***/
  85457. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85458. if (!this._sphere) {
  85459. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85460. this._sphere.isVisible = false;
  85461. }
  85462. };
  85463. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85464. var impostorObject = impostor.object;
  85465. this._prepareSphere();
  85466. this._sphere.position = origin;
  85467. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85468. this._sphere._updateBoundingInfo();
  85469. this._sphere.computeWorldMatrix(true);
  85470. return this._sphere.intersectsMesh(impostorObject, true);
  85471. };
  85472. return PhysicsRadialExplosionEvent;
  85473. }());
  85474. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85475. /***** Gravitational Field *****/
  85476. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85477. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85478. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85479. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85480. this._physicsHelper = physicsHelper;
  85481. this._scene = scene;
  85482. this._origin = origin;
  85483. this._radius = radius;
  85484. this._strength = strength;
  85485. this._falloff = falloff;
  85486. this._tickCallback = this._tick.bind(this);
  85487. }
  85488. /**
  85489. * Returns the data related to the gravitational field event (sphere).
  85490. * @returns {PhysicsGravitationalFieldEventData}
  85491. */
  85492. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85493. this._dataFetched = true;
  85494. return {
  85495. sphere: this._sphere,
  85496. };
  85497. };
  85498. /**
  85499. * Enables the gravitational field.
  85500. */
  85501. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85502. this._tickCallback.call(this);
  85503. this._scene.registerBeforeRender(this._tickCallback);
  85504. };
  85505. /**
  85506. * Disables the gravitational field.
  85507. */
  85508. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85509. this._scene.unregisterBeforeRender(this._tickCallback);
  85510. };
  85511. /**
  85512. * Disposes the sphere.
  85513. * @param {bolean} force
  85514. */
  85515. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85516. var _this = this;
  85517. if (force === void 0) { force = true; }
  85518. if (force) {
  85519. this._sphere.dispose();
  85520. }
  85521. else {
  85522. setTimeout(function () {
  85523. if (!_this._dataFetched) {
  85524. _this._sphere.dispose();
  85525. }
  85526. }, 0);
  85527. }
  85528. };
  85529. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85530. // Since the params won't change, we fetch the event only once
  85531. if (this._sphere) {
  85532. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85533. }
  85534. else {
  85535. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85536. if (radialExplosionEvent) {
  85537. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85538. }
  85539. }
  85540. };
  85541. return PhysicsGravitationalFieldEvent;
  85542. }());
  85543. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85544. /***** Updraft *****/
  85545. var PhysicsUpdraftEvent = /** @class */ (function () {
  85546. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85547. this._scene = _scene;
  85548. this._origin = _origin;
  85549. this._radius = _radius;
  85550. this._strength = _strength;
  85551. this._height = _height;
  85552. this._updraftMode = _updraftMode;
  85553. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85554. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85555. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85556. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85557. this._physicsEngine = this._scene.getPhysicsEngine();
  85558. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85559. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85560. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85561. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85562. }
  85563. this._tickCallback = this._tick.bind(this);
  85564. }
  85565. /**
  85566. * Returns the data related to the updraft event (cylinder).
  85567. * @returns {PhysicsUpdraftEventData}
  85568. */
  85569. PhysicsUpdraftEvent.prototype.getData = function () {
  85570. this._dataFetched = true;
  85571. return {
  85572. cylinder: this._cylinder,
  85573. };
  85574. };
  85575. /**
  85576. * Enables the updraft.
  85577. */
  85578. PhysicsUpdraftEvent.prototype.enable = function () {
  85579. this._tickCallback.call(this);
  85580. this._scene.registerBeforeRender(this._tickCallback);
  85581. };
  85582. /**
  85583. * Disables the cortex.
  85584. */
  85585. PhysicsUpdraftEvent.prototype.disable = function () {
  85586. this._scene.unregisterBeforeRender(this._tickCallback);
  85587. };
  85588. /**
  85589. * Disposes the sphere.
  85590. * @param {bolean} force
  85591. */
  85592. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85593. var _this = this;
  85594. if (force === void 0) { force = true; }
  85595. if (force) {
  85596. this._cylinder.dispose();
  85597. }
  85598. else {
  85599. setTimeout(function () {
  85600. if (!_this._dataFetched) {
  85601. _this._cylinder.dispose();
  85602. }
  85603. }, 0);
  85604. }
  85605. };
  85606. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85607. if (impostor.mass === 0) {
  85608. return null;
  85609. }
  85610. if (!this._intersectsWithCylinder(impostor)) {
  85611. return null;
  85612. }
  85613. var impostorObjectCenter = impostor.getObjectCenter();
  85614. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85615. var direction = this._originDirection;
  85616. }
  85617. else {
  85618. var direction = impostorObjectCenter.subtract(this._originTop);
  85619. }
  85620. var multiplier = this._strength * -1;
  85621. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85622. return { force: force, contactPoint: impostorObjectCenter };
  85623. };
  85624. PhysicsUpdraftEvent.prototype._tick = function () {
  85625. var _this = this;
  85626. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85627. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85628. if (!impostorForceAndContactPoint) {
  85629. return;
  85630. }
  85631. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85632. });
  85633. };
  85634. /*** Helpers ***/
  85635. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85636. if (!this._cylinder) {
  85637. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85638. height: this._height,
  85639. diameter: this._radius * 2,
  85640. }, this._scene);
  85641. this._cylinder.isVisible = false;
  85642. }
  85643. };
  85644. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85645. var impostorObject = impostor.object;
  85646. this._prepareCylinder();
  85647. this._cylinder.position = this._cylinderPosition;
  85648. return this._cylinder.intersectsMesh(impostorObject, true);
  85649. };
  85650. return PhysicsUpdraftEvent;
  85651. }());
  85652. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85653. /***** Vortex *****/
  85654. var PhysicsVortexEvent = /** @class */ (function () {
  85655. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85656. this._scene = _scene;
  85657. this._origin = _origin;
  85658. this._radius = _radius;
  85659. this._strength = _strength;
  85660. this._height = _height;
  85661. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85662. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85663. this._updraftMultiplier = 0.02;
  85664. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85665. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85666. this._physicsEngine = this._scene.getPhysicsEngine();
  85667. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85668. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85669. this._tickCallback = this._tick.bind(this);
  85670. }
  85671. /**
  85672. * Returns the data related to the vortex event (cylinder).
  85673. * @returns {PhysicsVortexEventData}
  85674. */
  85675. PhysicsVortexEvent.prototype.getData = function () {
  85676. this._dataFetched = true;
  85677. return {
  85678. cylinder: this._cylinder,
  85679. };
  85680. };
  85681. /**
  85682. * Enables the vortex.
  85683. */
  85684. PhysicsVortexEvent.prototype.enable = function () {
  85685. this._tickCallback.call(this);
  85686. this._scene.registerBeforeRender(this._tickCallback);
  85687. };
  85688. /**
  85689. * Disables the cortex.
  85690. */
  85691. PhysicsVortexEvent.prototype.disable = function () {
  85692. this._scene.unregisterBeforeRender(this._tickCallback);
  85693. };
  85694. /**
  85695. * Disposes the sphere.
  85696. * @param {bolean} force
  85697. */
  85698. PhysicsVortexEvent.prototype.dispose = function (force) {
  85699. var _this = this;
  85700. if (force === void 0) { force = true; }
  85701. if (force) {
  85702. this._cylinder.dispose();
  85703. }
  85704. else {
  85705. setTimeout(function () {
  85706. if (!_this._dataFetched) {
  85707. _this._cylinder.dispose();
  85708. }
  85709. }, 0);
  85710. }
  85711. };
  85712. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85713. if (impostor.mass === 0) {
  85714. return null;
  85715. }
  85716. if (!this._intersectsWithCylinder(impostor)) {
  85717. return null;
  85718. }
  85719. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85720. return null;
  85721. }
  85722. var impostorObjectCenter = impostor.getObjectCenter();
  85723. 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)
  85724. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85725. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85726. var hit = ray.intersectsMesh(impostor.object);
  85727. var contactPoint = hit.pickedPoint;
  85728. if (!contactPoint) {
  85729. return null;
  85730. }
  85731. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85732. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85733. var directionToOrigin = contactPoint.normalize();
  85734. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85735. directionToOrigin = directionToOrigin.negate();
  85736. }
  85737. // TODO: find a more physically based solution
  85738. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85739. var forceX = directionToOrigin.x * this._strength / 8;
  85740. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85741. var forceZ = directionToOrigin.z * this._strength / 8;
  85742. }
  85743. else {
  85744. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85745. var forceY = this._originTop.y * this._updraftMultiplier;
  85746. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85747. }
  85748. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85749. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85750. return { force: force, contactPoint: impostorObjectCenter };
  85751. };
  85752. PhysicsVortexEvent.prototype._tick = function () {
  85753. var _this = this;
  85754. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85755. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85756. if (!impostorForceAndContactPoint) {
  85757. return;
  85758. }
  85759. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85760. });
  85761. };
  85762. /*** Helpers ***/
  85763. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85764. if (!this._cylinder) {
  85765. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85766. height: this._height,
  85767. diameter: this._radius * 2,
  85768. }, this._scene);
  85769. this._cylinder.isVisible = false;
  85770. }
  85771. };
  85772. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85773. var impostorObject = impostor.object;
  85774. this._prepareCylinder();
  85775. this._cylinder.position = this._cylinderPosition;
  85776. return this._cylinder.intersectsMesh(impostorObject, true);
  85777. };
  85778. return PhysicsVortexEvent;
  85779. }());
  85780. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85781. /***** Enums *****/
  85782. /**
  85783. * The strenght of the force in correspondence to the distance of the affected object
  85784. */
  85785. var PhysicsRadialImpulseFalloff;
  85786. (function (PhysicsRadialImpulseFalloff) {
  85787. /** Defines that impulse is constant in strength across it's whole radius */
  85788. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85789. /** DEfines that impulse gets weaker if it's further from the origin */
  85790. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85791. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85792. /**
  85793. * The strenght of the force in correspondence to the distance of the affected object
  85794. */
  85795. var PhysicsUpdraftMode;
  85796. (function (PhysicsUpdraftMode) {
  85797. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85798. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85799. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85800. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85801. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85802. })(BABYLON || (BABYLON = {}));
  85803. //# sourceMappingURL=babylon.physicsHelper.js.map
  85804. var BABYLON;
  85805. (function (BABYLON) {
  85806. var CannonJSPlugin = /** @class */ (function () {
  85807. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85808. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85809. if (iterations === void 0) { iterations = 10; }
  85810. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85811. this.name = "CannonJSPlugin";
  85812. this._physicsMaterials = new Array();
  85813. this._fixedTimeStep = 1 / 60;
  85814. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85815. this.BJSCANNON = CANNON;
  85816. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85817. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85818. this._tmpPosition = BABYLON.Vector3.Zero();
  85819. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85820. this._tmpUnityRotation = new BABYLON.Quaternion();
  85821. if (!this.isSupported()) {
  85822. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85823. return;
  85824. }
  85825. this._extendNamespace();
  85826. this.world = new this.BJSCANNON.World();
  85827. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85828. this.world.solver.iterations = iterations;
  85829. }
  85830. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85831. this.world.gravity.copy(gravity);
  85832. };
  85833. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85834. this._fixedTimeStep = timeStep;
  85835. };
  85836. CannonJSPlugin.prototype.getTimeStep = function () {
  85837. return this._fixedTimeStep;
  85838. };
  85839. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85840. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85841. };
  85842. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85843. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85844. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85845. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85846. };
  85847. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85848. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85849. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85850. impostor.physicsBody.applyForce(impulse, worldPoint);
  85851. };
  85852. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85853. //parent-child relationship. Does this impostor has a parent impostor?
  85854. if (impostor.parent) {
  85855. if (impostor.physicsBody) {
  85856. this.removePhysicsBody(impostor);
  85857. //TODO is that needed?
  85858. impostor.forceUpdate();
  85859. }
  85860. return;
  85861. }
  85862. //should a new body be created for this impostor?
  85863. if (impostor.isBodyInitRequired()) {
  85864. var shape = this._createShape(impostor);
  85865. //unregister events, if body is being changed
  85866. var oldBody = impostor.physicsBody;
  85867. if (oldBody) {
  85868. this.removePhysicsBody(impostor);
  85869. }
  85870. //create the body and material
  85871. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85872. var bodyCreationObject = {
  85873. mass: impostor.getParam("mass"),
  85874. material: material
  85875. };
  85876. // A simple extend, in case native options were used.
  85877. var nativeOptions = impostor.getParam("nativeOptions");
  85878. for (var key in nativeOptions) {
  85879. if (nativeOptions.hasOwnProperty(key)) {
  85880. bodyCreationObject[key] = nativeOptions[key];
  85881. }
  85882. }
  85883. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85884. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85885. this.world.addEventListener("preStep", impostor.beforeStep);
  85886. this.world.addEventListener("postStep", impostor.afterStep);
  85887. impostor.physicsBody.addShape(shape);
  85888. this.world.add(impostor.physicsBody);
  85889. //try to keep the body moving in the right direction by taking old properties.
  85890. //Should be tested!
  85891. if (oldBody) {
  85892. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85893. impostor.physicsBody[param].copy(oldBody[param]);
  85894. });
  85895. }
  85896. this._processChildMeshes(impostor);
  85897. }
  85898. //now update the body's transformation
  85899. this._updatePhysicsBodyTransformation(impostor);
  85900. };
  85901. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85902. var _this = this;
  85903. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85904. var currentRotation = mainImpostor.object.rotationQuaternion;
  85905. if (meshChildren.length) {
  85906. var processMesh = function (localPosition, mesh) {
  85907. if (!currentRotation || !mesh.rotationQuaternion) {
  85908. return;
  85909. }
  85910. var childImpostor = mesh.getPhysicsImpostor();
  85911. if (childImpostor) {
  85912. var parent = childImpostor.parent;
  85913. if (parent !== mainImpostor) {
  85914. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85915. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85916. if (childImpostor.physicsBody) {
  85917. _this.removePhysicsBody(childImpostor);
  85918. childImpostor.physicsBody = null;
  85919. }
  85920. childImpostor.parent = mainImpostor;
  85921. childImpostor.resetUpdateFlags();
  85922. 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));
  85923. //Add the mass of the children.
  85924. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85925. }
  85926. }
  85927. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85928. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85929. };
  85930. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85931. }
  85932. };
  85933. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85934. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85935. this.world.removeEventListener("preStep", impostor.beforeStep);
  85936. this.world.removeEventListener("postStep", impostor.afterStep);
  85937. this.world.remove(impostor.physicsBody);
  85938. };
  85939. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85942. if (!mainBody || !connectedBody) {
  85943. return;
  85944. }
  85945. var constraint;
  85946. var jointData = impostorJoint.joint.jointData;
  85947. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85948. var constraintData = {
  85949. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85950. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85951. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85952. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85953. maxForce: jointData.nativeParams.maxForce,
  85954. collideConnected: !!jointData.collision
  85955. };
  85956. switch (impostorJoint.joint.type) {
  85957. case BABYLON.PhysicsJoint.HingeJoint:
  85958. case BABYLON.PhysicsJoint.Hinge2Joint:
  85959. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85960. break;
  85961. case BABYLON.PhysicsJoint.DistanceJoint:
  85962. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85963. break;
  85964. case BABYLON.PhysicsJoint.SpringJoint:
  85965. var springData = jointData;
  85966. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85967. restLength: springData.length,
  85968. stiffness: springData.stiffness,
  85969. damping: springData.damping,
  85970. localAnchorA: constraintData.pivotA,
  85971. localAnchorB: constraintData.pivotB
  85972. });
  85973. break;
  85974. case BABYLON.PhysicsJoint.LockJoint:
  85975. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85976. break;
  85977. case BABYLON.PhysicsJoint.PointToPointJoint:
  85978. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85979. default:
  85980. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85981. break;
  85982. }
  85983. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85984. constraint.collideConnected = !!jointData.collision;
  85985. impostorJoint.joint.physicsJoint = constraint;
  85986. //don't add spring as constraint, as it is not one.
  85987. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85988. this.world.addConstraint(constraint);
  85989. }
  85990. else {
  85991. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85992. constraint.applyForce();
  85993. });
  85994. }
  85995. };
  85996. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85997. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85998. };
  85999. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86000. var index;
  86001. var mat;
  86002. for (index = 0; index < this._physicsMaterials.length; index++) {
  86003. mat = this._physicsMaterials[index];
  86004. if (mat.friction === friction && mat.restitution === restitution) {
  86005. return mat;
  86006. }
  86007. }
  86008. var currentMat = new this.BJSCANNON.Material(name);
  86009. currentMat.friction = friction;
  86010. currentMat.restitution = restitution;
  86011. this._physicsMaterials.push(currentMat);
  86012. return currentMat;
  86013. };
  86014. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86015. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86016. };
  86017. CannonJSPlugin.prototype._createShape = function (impostor) {
  86018. var object = impostor.object;
  86019. var returnValue;
  86020. var extendSize = impostor.getObjectExtendSize();
  86021. switch (impostor.type) {
  86022. case BABYLON.PhysicsImpostor.SphereImpostor:
  86023. var radiusX = extendSize.x;
  86024. var radiusY = extendSize.y;
  86025. var radiusZ = extendSize.z;
  86026. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86027. break;
  86028. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86029. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86030. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86031. break;
  86032. case BABYLON.PhysicsImpostor.BoxImpostor:
  86033. var box = extendSize.scale(0.5);
  86034. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86035. break;
  86036. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86037. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86038. returnValue = new this.BJSCANNON.Plane();
  86039. break;
  86040. case BABYLON.PhysicsImpostor.MeshImpostor:
  86041. // should transform the vertex data to world coordinates!!
  86042. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86043. var rawFaces = object.getIndices ? object.getIndices() : [];
  86044. if (!rawVerts)
  86045. return;
  86046. // get only scale! so the object could transform correctly.
  86047. var oldPosition = object.position.clone();
  86048. var oldRotation = object.rotation && object.rotation.clone();
  86049. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86050. object.position.copyFromFloats(0, 0, 0);
  86051. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86052. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86053. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86054. var transform = object.computeWorldMatrix(true);
  86055. // convert rawVerts to object space
  86056. var temp = new Array();
  86057. var index;
  86058. for (index = 0; index < rawVerts.length; index += 3) {
  86059. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86060. }
  86061. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86062. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86063. //now set back the transformation!
  86064. object.position.copyFrom(oldPosition);
  86065. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86066. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86067. break;
  86068. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86069. var oldPosition2 = object.position.clone();
  86070. var oldRotation2 = object.rotation && object.rotation.clone();
  86071. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86072. object.position.copyFromFloats(0, 0, 0);
  86073. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86074. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86075. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86076. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86077. returnValue = this._createHeightmap(object);
  86078. object.position.copyFrom(oldPosition2);
  86079. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86080. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86081. object.computeWorldMatrix(true);
  86082. break;
  86083. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86084. returnValue = new this.BJSCANNON.Particle();
  86085. break;
  86086. }
  86087. return returnValue;
  86088. };
  86089. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86090. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86091. var transform = object.computeWorldMatrix(true);
  86092. // convert rawVerts to object space
  86093. var temp = new Array();
  86094. var index;
  86095. for (index = 0; index < pos.length; index += 3) {
  86096. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86097. }
  86098. pos = temp;
  86099. var matrix = new Array();
  86100. //For now pointDepth will not be used and will be automatically calculated.
  86101. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86102. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86103. var boundingInfo = object.getBoundingInfo();
  86104. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86105. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86106. var elementSize = dim * 2 / arraySize;
  86107. for (var i = 0; i < pos.length; i = i + 3) {
  86108. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86109. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86110. var y = -pos[i + 2] + minY;
  86111. if (!matrix[x]) {
  86112. matrix[x] = [];
  86113. }
  86114. if (!matrix[x][z]) {
  86115. matrix[x][z] = y;
  86116. }
  86117. matrix[x][z] = Math.max(y, matrix[x][z]);
  86118. }
  86119. for (var x = 0; x <= arraySize; ++x) {
  86120. if (!matrix[x]) {
  86121. var loc = 1;
  86122. while (!matrix[(x + loc) % arraySize]) {
  86123. loc++;
  86124. }
  86125. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86126. //console.log("missing x", x);
  86127. }
  86128. for (var z = 0; z <= arraySize; ++z) {
  86129. if (!matrix[x][z]) {
  86130. var loc = 1;
  86131. var newValue;
  86132. while (newValue === undefined) {
  86133. newValue = matrix[x][(z + loc++) % arraySize];
  86134. }
  86135. matrix[x][z] = newValue;
  86136. }
  86137. }
  86138. }
  86139. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86140. elementSize: elementSize
  86141. });
  86142. //For future reference, needed for body transformation
  86143. shape.minY = minY;
  86144. return shape;
  86145. };
  86146. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86147. var object = impostor.object;
  86148. //make sure it is updated...
  86149. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86150. // The delta between the mesh position and the mesh bounding box center
  86151. var bInfo = object.getBoundingInfo();
  86152. if (!bInfo)
  86153. return;
  86154. var center = impostor.getObjectCenter();
  86155. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86156. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86157. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86158. this._tmpPosition.copyFrom(center);
  86159. var quaternion = object.rotationQuaternion;
  86160. if (!quaternion) {
  86161. return;
  86162. }
  86163. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86164. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86165. //-90 DEG in X, precalculated
  86166. quaternion = quaternion.multiply(this._minus90X);
  86167. //Invert! (Precalculated, 90 deg in X)
  86168. //No need to clone. this will never change.
  86169. impostor.setDeltaRotation(this._plus90X);
  86170. }
  86171. //If it is a heightfield, if should be centered.
  86172. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86173. var mesh = object;
  86174. var boundingInfo = mesh.getBoundingInfo();
  86175. //calculate the correct body position:
  86176. var rotationQuaternion = mesh.rotationQuaternion;
  86177. mesh.rotationQuaternion = this._tmpUnityRotation;
  86178. mesh.computeWorldMatrix(true);
  86179. //get original center with no rotation
  86180. var c = center.clone();
  86181. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86182. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86183. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86184. mesh.setPreTransformMatrix(p);
  86185. mesh.computeWorldMatrix(true);
  86186. //calculate the translation
  86187. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86188. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86189. //add it inverted to the delta
  86190. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86191. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86192. //rotation is back
  86193. mesh.rotationQuaternion = rotationQuaternion;
  86194. mesh.setPreTransformMatrix(oldPivot);
  86195. mesh.computeWorldMatrix(true);
  86196. }
  86197. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86198. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86199. //this._tmpPosition.copyFrom(object.position);
  86200. }
  86201. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86202. //Now update the impostor object
  86203. impostor.physicsBody.position.copy(this._tmpPosition);
  86204. impostor.physicsBody.quaternion.copy(quaternion);
  86205. };
  86206. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86207. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86208. if (impostor.object.rotationQuaternion) {
  86209. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86210. }
  86211. };
  86212. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86213. impostor.physicsBody.position.copy(newPosition);
  86214. impostor.physicsBody.quaternion.copy(newRotation);
  86215. };
  86216. CannonJSPlugin.prototype.isSupported = function () {
  86217. return this.BJSCANNON !== undefined;
  86218. };
  86219. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86220. impostor.physicsBody.velocity.copy(velocity);
  86221. };
  86222. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86223. impostor.physicsBody.angularVelocity.copy(velocity);
  86224. };
  86225. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86226. var v = impostor.physicsBody.velocity;
  86227. if (!v) {
  86228. return null;
  86229. }
  86230. return new BABYLON.Vector3(v.x, v.y, v.z);
  86231. };
  86232. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86233. var v = impostor.physicsBody.angularVelocity;
  86234. if (!v) {
  86235. return null;
  86236. }
  86237. return new BABYLON.Vector3(v.x, v.y, v.z);
  86238. };
  86239. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86240. impostor.physicsBody.mass = mass;
  86241. impostor.physicsBody.updateMassProperties();
  86242. };
  86243. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86244. return impostor.physicsBody.mass;
  86245. };
  86246. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86247. return impostor.physicsBody.material.friction;
  86248. };
  86249. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86250. impostor.physicsBody.material.friction = friction;
  86251. };
  86252. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86253. return impostor.physicsBody.material.restitution;
  86254. };
  86255. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86256. impostor.physicsBody.material.restitution = restitution;
  86257. };
  86258. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86259. impostor.physicsBody.sleep();
  86260. };
  86261. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86262. impostor.physicsBody.wakeUp();
  86263. };
  86264. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86265. joint.physicsJoint.distance = maxDistance;
  86266. };
  86267. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86268. // if (!motorIndex) {
  86269. // joint.physicsJoint.enableMotor();
  86270. // }
  86271. // }
  86272. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86273. // if (!motorIndex) {
  86274. // joint.physicsJoint.disableMotor();
  86275. // }
  86276. // }
  86277. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86278. if (!motorIndex) {
  86279. joint.physicsJoint.enableMotor();
  86280. joint.physicsJoint.setMotorSpeed(speed);
  86281. if (maxForce) {
  86282. this.setLimit(joint, maxForce);
  86283. }
  86284. }
  86285. };
  86286. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86287. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86288. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86289. };
  86290. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86291. var body = impostor.physicsBody;
  86292. mesh.position.x = body.position.x;
  86293. mesh.position.y = body.position.y;
  86294. mesh.position.z = body.position.z;
  86295. if (mesh.rotationQuaternion) {
  86296. mesh.rotationQuaternion.x = body.quaternion.x;
  86297. mesh.rotationQuaternion.y = body.quaternion.y;
  86298. mesh.rotationQuaternion.z = body.quaternion.z;
  86299. mesh.rotationQuaternion.w = body.quaternion.w;
  86300. }
  86301. };
  86302. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86303. var shape = impostor.physicsBody.shapes[0];
  86304. return shape.boundingSphereRadius;
  86305. };
  86306. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86307. var shape = impostor.physicsBody.shapes[0];
  86308. result.x = shape.halfExtents.x * 2;
  86309. result.y = shape.halfExtents.y * 2;
  86310. result.z = shape.halfExtents.z * 2;
  86311. };
  86312. CannonJSPlugin.prototype.dispose = function () {
  86313. };
  86314. CannonJSPlugin.prototype._extendNamespace = function () {
  86315. //this will force cannon to execute at least one step when using interpolation
  86316. var step_tmp1 = new this.BJSCANNON.Vec3();
  86317. var Engine = this.BJSCANNON;
  86318. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86319. maxSubSteps = maxSubSteps || 10;
  86320. timeSinceLastCalled = timeSinceLastCalled || 0;
  86321. if (timeSinceLastCalled === 0) {
  86322. this.internalStep(dt);
  86323. this.time += dt;
  86324. }
  86325. else {
  86326. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86327. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86328. var t0 = performance.now();
  86329. for (var i = 0; i !== internalSteps; i++) {
  86330. this.internalStep(dt);
  86331. if (performance.now() - t0 > dt * 1000) {
  86332. break;
  86333. }
  86334. }
  86335. this.time += timeSinceLastCalled;
  86336. var h = this.time % dt;
  86337. var h_div_dt = h / dt;
  86338. var interpvelo = step_tmp1;
  86339. var bodies = this.bodies;
  86340. for (var j = 0; j !== bodies.length; j++) {
  86341. var b = bodies[j];
  86342. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86343. b.position.vsub(b.previousPosition, interpvelo);
  86344. interpvelo.scale(h_div_dt, interpvelo);
  86345. b.position.vadd(interpvelo, b.interpolatedPosition);
  86346. }
  86347. else {
  86348. b.interpolatedPosition.copy(b.position);
  86349. b.interpolatedQuaternion.copy(b.quaternion);
  86350. }
  86351. }
  86352. }
  86353. };
  86354. };
  86355. return CannonJSPlugin;
  86356. }());
  86357. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86358. })(BABYLON || (BABYLON = {}));
  86359. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86360. var BABYLON;
  86361. (function (BABYLON) {
  86362. var OimoJSPlugin = /** @class */ (function () {
  86363. function OimoJSPlugin(iterations) {
  86364. this.name = "OimoJSPlugin";
  86365. this._tmpImpostorsArray = [];
  86366. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86367. this.BJSOIMO = OIMO;
  86368. this.world = new this.BJSOIMO.World({
  86369. iterations: iterations
  86370. });
  86371. this.world.clear();
  86372. }
  86373. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86374. this.world.gravity.copy(gravity);
  86375. };
  86376. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86377. this.world.timeStep = timeStep;
  86378. };
  86379. OimoJSPlugin.prototype.getTimeStep = function () {
  86380. return this.world.timeStep;
  86381. };
  86382. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86383. var _this = this;
  86384. impostors.forEach(function (impostor) {
  86385. impostor.beforeStep();
  86386. });
  86387. this.world.step();
  86388. impostors.forEach(function (impostor) {
  86389. impostor.afterStep();
  86390. //update the ordered impostors array
  86391. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86392. });
  86393. //check for collisions
  86394. var contact = this.world.contacts;
  86395. while (contact !== null) {
  86396. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86397. contact = contact.next;
  86398. continue;
  86399. }
  86400. //is this body colliding with any other? get the impostor
  86401. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86402. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86403. if (!mainImpostor || !collidingImpostor) {
  86404. contact = contact.next;
  86405. continue;
  86406. }
  86407. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86408. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86409. contact = contact.next;
  86410. }
  86411. };
  86412. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86413. var mass = impostor.physicsBody.mass;
  86414. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86415. };
  86416. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86417. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86418. this.applyImpulse(impostor, force, contactPoint);
  86419. };
  86420. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86421. var _this = this;
  86422. //parent-child relationship. Does this impostor has a parent impostor?
  86423. if (impostor.parent) {
  86424. if (impostor.physicsBody) {
  86425. this.removePhysicsBody(impostor);
  86426. //TODO is that needed?
  86427. impostor.forceUpdate();
  86428. }
  86429. return;
  86430. }
  86431. if (impostor.isBodyInitRequired()) {
  86432. var bodyConfig = {
  86433. name: impostor.uniqueId,
  86434. //Oimo must have mass, also for static objects.
  86435. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86436. size: [],
  86437. type: [],
  86438. pos: [],
  86439. posShape: [],
  86440. rot: [],
  86441. rotShape: [],
  86442. move: impostor.getParam("mass") !== 0,
  86443. density: impostor.getParam("mass"),
  86444. friction: impostor.getParam("friction"),
  86445. restitution: impostor.getParam("restitution"),
  86446. //Supporting older versions of Oimo
  86447. world: this.world
  86448. };
  86449. var impostors = [impostor];
  86450. var addToArray = function (parent) {
  86451. if (!parent.getChildMeshes)
  86452. return;
  86453. parent.getChildMeshes().forEach(function (m) {
  86454. if (m.physicsImpostor) {
  86455. impostors.push(m.physicsImpostor);
  86456. //m.physicsImpostor._init();
  86457. }
  86458. });
  86459. };
  86460. addToArray(impostor.object);
  86461. var checkWithEpsilon_1 = function (value) {
  86462. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86463. };
  86464. impostors.forEach(function (i) {
  86465. if (!i.object.rotationQuaternion) {
  86466. return;
  86467. }
  86468. //get the correct bounding box
  86469. var oldQuaternion = i.object.rotationQuaternion;
  86470. var rot = oldQuaternion.toEulerAngles();
  86471. var extendSize = i.getObjectExtendSize();
  86472. var radToDeg = 57.295779513082320876;
  86473. if (i === impostor) {
  86474. var center = impostor.getObjectCenter();
  86475. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86476. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86477. //Can also use Array.prototype.push.apply
  86478. bodyConfig.pos.push(center.x);
  86479. bodyConfig.pos.push(center.y);
  86480. bodyConfig.pos.push(center.z);
  86481. bodyConfig.posShape.push(0, 0, 0);
  86482. //tmp solution
  86483. bodyConfig.rot.push(rot.x * radToDeg);
  86484. bodyConfig.rot.push(rot.y * radToDeg);
  86485. bodyConfig.rot.push(rot.z * radToDeg);
  86486. bodyConfig.rotShape.push(0, 0, 0);
  86487. }
  86488. else {
  86489. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86490. bodyConfig.posShape.push(localPosition.x);
  86491. bodyConfig.posShape.push(localPosition.y);
  86492. bodyConfig.posShape.push(localPosition.z);
  86493. bodyConfig.pos.push(0, 0, 0);
  86494. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86495. bodyConfig.rot.push(0);
  86496. bodyConfig.rot.push(0);
  86497. bodyConfig.rot.push(0);
  86498. bodyConfig.rotShape.push(rot.x * radToDeg);
  86499. bodyConfig.rotShape.push(rot.y * radToDeg);
  86500. bodyConfig.rotShape.push(rot.z * radToDeg);
  86501. }
  86502. // register mesh
  86503. switch (i.type) {
  86504. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86505. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86506. case BABYLON.PhysicsImpostor.SphereImpostor:
  86507. var radiusX = extendSize.x;
  86508. var radiusY = extendSize.y;
  86509. var radiusZ = extendSize.z;
  86510. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86511. bodyConfig.type.push('sphere');
  86512. //due to the way oimo works with compounds, add 3 times
  86513. bodyConfig.size.push(size);
  86514. bodyConfig.size.push(size);
  86515. bodyConfig.size.push(size);
  86516. break;
  86517. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86518. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86519. var sizeY = checkWithEpsilon_1(extendSize.y);
  86520. bodyConfig.type.push('cylinder');
  86521. bodyConfig.size.push(sizeX);
  86522. bodyConfig.size.push(sizeY);
  86523. //due to the way oimo works with compounds, add one more value.
  86524. bodyConfig.size.push(sizeY);
  86525. break;
  86526. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86527. case BABYLON.PhysicsImpostor.BoxImpostor:
  86528. default:
  86529. var sizeX = checkWithEpsilon_1(extendSize.x);
  86530. var sizeY = checkWithEpsilon_1(extendSize.y);
  86531. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86532. bodyConfig.type.push('box');
  86533. //if (i === impostor) {
  86534. bodyConfig.size.push(sizeX);
  86535. bodyConfig.size.push(sizeY);
  86536. bodyConfig.size.push(sizeZ);
  86537. //} else {
  86538. // bodyConfig.size.push(0,0,0);
  86539. //}
  86540. break;
  86541. }
  86542. //actually not needed, but hey...
  86543. i.object.rotationQuaternion = oldQuaternion;
  86544. });
  86545. impostor.physicsBody = this.world.add(bodyConfig);
  86546. }
  86547. else {
  86548. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86549. }
  86550. impostor.setDeltaPosition(this._tmpPositionVector);
  86551. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86552. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86553. };
  86554. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86555. //impostor.physicsBody.dispose();
  86556. //Same as : (older oimo versions)
  86557. this.world.removeRigidBody(impostor.physicsBody);
  86558. };
  86559. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86560. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86561. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86562. if (!mainBody || !connectedBody) {
  86563. return;
  86564. }
  86565. var jointData = impostorJoint.joint.jointData;
  86566. var options = jointData.nativeParams || {};
  86567. var type;
  86568. var nativeJointData = {
  86569. body1: mainBody,
  86570. body2: connectedBody,
  86571. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86572. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86573. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86574. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86575. min: options.min,
  86576. max: options.max,
  86577. collision: options.collision || jointData.collision,
  86578. spring: options.spring,
  86579. //supporting older version of Oimo
  86580. world: this.world
  86581. };
  86582. switch (impostorJoint.joint.type) {
  86583. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86584. type = "jointBall";
  86585. break;
  86586. case BABYLON.PhysicsJoint.SpringJoint:
  86587. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86588. var springData = jointData;
  86589. nativeJointData.min = springData.length || nativeJointData.min;
  86590. //Max should also be set, just make sure it is at least min
  86591. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86592. case BABYLON.PhysicsJoint.DistanceJoint:
  86593. type = "jointDistance";
  86594. nativeJointData.max = jointData.maxDistance;
  86595. break;
  86596. case BABYLON.PhysicsJoint.PrismaticJoint:
  86597. type = "jointPrisme";
  86598. break;
  86599. case BABYLON.PhysicsJoint.SliderJoint:
  86600. type = "jointSlide";
  86601. break;
  86602. case BABYLON.PhysicsJoint.WheelJoint:
  86603. type = "jointWheel";
  86604. break;
  86605. case BABYLON.PhysicsJoint.HingeJoint:
  86606. default:
  86607. type = "jointHinge";
  86608. break;
  86609. }
  86610. nativeJointData.type = type;
  86611. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86612. };
  86613. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86614. //Bug in Oimo prevents us from disposing a joint in the playground
  86615. //joint.joint.physicsJoint.dispose();
  86616. //So we will bruteforce it!
  86617. try {
  86618. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86619. }
  86620. catch (e) {
  86621. BABYLON.Tools.Warn(e);
  86622. }
  86623. };
  86624. OimoJSPlugin.prototype.isSupported = function () {
  86625. return this.BJSOIMO !== undefined;
  86626. };
  86627. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86628. if (!impostor.physicsBody.sleeping) {
  86629. //TODO check that
  86630. /*if (impostor.physicsBody.shapes.next) {
  86631. var parentShape = this._getLastShape(impostor.physicsBody);
  86632. impostor.object.position.copyFrom(parentShape.position);
  86633. console.log(parentShape.position);
  86634. } else {*/
  86635. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86636. //}
  86637. if (impostor.object.rotationQuaternion) {
  86638. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86639. }
  86640. }
  86641. };
  86642. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86643. var body = impostor.physicsBody;
  86644. body.position.copy(newPosition);
  86645. body.orientation.copy(newRotation);
  86646. body.syncShapes();
  86647. body.awake();
  86648. };
  86649. /*private _getLastShape(body: any): any {
  86650. var lastShape = body.shapes;
  86651. while (lastShape.next) {
  86652. lastShape = lastShape.next;
  86653. }
  86654. return lastShape;
  86655. }*/
  86656. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86657. impostor.physicsBody.linearVelocity.copy(velocity);
  86658. };
  86659. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86660. impostor.physicsBody.angularVelocity.copy(velocity);
  86661. };
  86662. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86663. var v = impostor.physicsBody.linearVelocity;
  86664. if (!v) {
  86665. return null;
  86666. }
  86667. return new BABYLON.Vector3(v.x, v.y, v.z);
  86668. };
  86669. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86670. var v = impostor.physicsBody.angularVelocity;
  86671. if (!v) {
  86672. return null;
  86673. }
  86674. return new BABYLON.Vector3(v.x, v.y, v.z);
  86675. };
  86676. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86677. var staticBody = mass === 0;
  86678. //this will actually set the body's density and not its mass.
  86679. //But this is how oimo treats the mass variable.
  86680. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86681. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86682. };
  86683. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86684. return impostor.physicsBody.shapes.density;
  86685. };
  86686. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86687. return impostor.physicsBody.shapes.friction;
  86688. };
  86689. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86690. impostor.physicsBody.shapes.friction = friction;
  86691. };
  86692. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86693. return impostor.physicsBody.shapes.restitution;
  86694. };
  86695. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86696. impostor.physicsBody.shapes.restitution = restitution;
  86697. };
  86698. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86699. impostor.physicsBody.sleep();
  86700. };
  86701. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86702. impostor.physicsBody.awake();
  86703. };
  86704. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86705. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86706. if (minDistance !== void 0) {
  86707. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86708. }
  86709. };
  86710. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86711. //TODO separate rotational and transational motors.
  86712. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86713. if (motor) {
  86714. motor.setMotor(speed, maxForce);
  86715. }
  86716. };
  86717. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86718. //TODO separate rotational and transational motors.
  86719. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86720. if (motor) {
  86721. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86722. }
  86723. };
  86724. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86725. var body = impostor.physicsBody;
  86726. mesh.position.x = body.position.x;
  86727. mesh.position.y = body.position.y;
  86728. mesh.position.z = body.position.z;
  86729. if (mesh.rotationQuaternion) {
  86730. mesh.rotationQuaternion.x = body.orientation.x;
  86731. mesh.rotationQuaternion.y = body.orientation.y;
  86732. mesh.rotationQuaternion.z = body.orientation.z;
  86733. mesh.rotationQuaternion.w = body.orientation.s;
  86734. }
  86735. };
  86736. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86737. return impostor.physicsBody.shapes.radius;
  86738. };
  86739. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86740. var shape = impostor.physicsBody.shapes;
  86741. result.x = shape.halfWidth * 2;
  86742. result.y = shape.halfHeight * 2;
  86743. result.z = shape.halfDepth * 2;
  86744. };
  86745. OimoJSPlugin.prototype.dispose = function () {
  86746. this.world.clear();
  86747. };
  86748. return OimoJSPlugin;
  86749. }());
  86750. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86751. })(BABYLON || (BABYLON = {}));
  86752. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86753. var BABYLON;
  86754. (function (BABYLON) {
  86755. /*
  86756. * Based on jsTGALoader - Javascript loader for TGA file
  86757. * By Vincent Thibault
  86758. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86759. */
  86760. var TGATools = /** @class */ (function () {
  86761. function TGATools() {
  86762. }
  86763. TGATools.GetTGAHeader = function (data) {
  86764. var offset = 0;
  86765. var header = {
  86766. id_length: data[offset++],
  86767. colormap_type: data[offset++],
  86768. image_type: data[offset++],
  86769. colormap_index: data[offset++] | data[offset++] << 8,
  86770. colormap_length: data[offset++] | data[offset++] << 8,
  86771. colormap_size: data[offset++],
  86772. origin: [
  86773. data[offset++] | data[offset++] << 8,
  86774. data[offset++] | data[offset++] << 8
  86775. ],
  86776. width: data[offset++] | data[offset++] << 8,
  86777. height: data[offset++] | data[offset++] << 8,
  86778. pixel_size: data[offset++],
  86779. flags: data[offset++]
  86780. };
  86781. return header;
  86782. };
  86783. /**
  86784. * Uploads TGA content to a Babylon Texture
  86785. * @hidden
  86786. */
  86787. TGATools.UploadContent = function (texture, data) {
  86788. // Not enough data to contain header ?
  86789. if (data.length < 19) {
  86790. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86791. return;
  86792. }
  86793. // Read Header
  86794. var offset = 18;
  86795. var header = TGATools.GetTGAHeader(data);
  86796. // Assume it's a valid Targa file.
  86797. if (header.id_length + offset > data.length) {
  86798. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86799. return;
  86800. }
  86801. // Skip not needed data
  86802. offset += header.id_length;
  86803. var use_rle = false;
  86804. var use_pal = false;
  86805. var use_grey = false;
  86806. // Get some informations.
  86807. switch (header.image_type) {
  86808. case TGATools._TYPE_RLE_INDEXED:
  86809. use_rle = true;
  86810. case TGATools._TYPE_INDEXED:
  86811. use_pal = true;
  86812. break;
  86813. case TGATools._TYPE_RLE_RGB:
  86814. use_rle = true;
  86815. case TGATools._TYPE_RGB:
  86816. // use_rgb = true;
  86817. break;
  86818. case TGATools._TYPE_RLE_GREY:
  86819. use_rle = true;
  86820. case TGATools._TYPE_GREY:
  86821. use_grey = true;
  86822. break;
  86823. }
  86824. var pixel_data;
  86825. // var numAlphaBits = header.flags & 0xf;
  86826. var pixel_size = header.pixel_size >> 3;
  86827. var pixel_total = header.width * header.height * pixel_size;
  86828. // Read palettes
  86829. var palettes;
  86830. if (use_pal) {
  86831. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86832. }
  86833. // Read LRE
  86834. if (use_rle) {
  86835. pixel_data = new Uint8Array(pixel_total);
  86836. var c, count, i;
  86837. var localOffset = 0;
  86838. var pixels = new Uint8Array(pixel_size);
  86839. while (offset < pixel_total && localOffset < pixel_total) {
  86840. c = data[offset++];
  86841. count = (c & 0x7f) + 1;
  86842. // RLE pixels
  86843. if (c & 0x80) {
  86844. // Bind pixel tmp array
  86845. for (i = 0; i < pixel_size; ++i) {
  86846. pixels[i] = data[offset++];
  86847. }
  86848. // Copy pixel array
  86849. for (i = 0; i < count; ++i) {
  86850. pixel_data.set(pixels, localOffset + i * pixel_size);
  86851. }
  86852. localOffset += pixel_size * count;
  86853. }
  86854. // Raw pixels
  86855. else {
  86856. count *= pixel_size;
  86857. for (i = 0; i < count; ++i) {
  86858. pixel_data[localOffset + i] = data[offset++];
  86859. }
  86860. localOffset += count;
  86861. }
  86862. }
  86863. }
  86864. // RAW Pixels
  86865. else {
  86866. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86867. }
  86868. // Load to texture
  86869. var x_start, y_start, x_step, y_step, y_end, x_end;
  86870. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86871. default:
  86872. case TGATools._ORIGIN_UL:
  86873. x_start = 0;
  86874. x_step = 1;
  86875. x_end = header.width;
  86876. y_start = 0;
  86877. y_step = 1;
  86878. y_end = header.height;
  86879. break;
  86880. case TGATools._ORIGIN_BL:
  86881. x_start = 0;
  86882. x_step = 1;
  86883. x_end = header.width;
  86884. y_start = header.height - 1;
  86885. y_step = -1;
  86886. y_end = -1;
  86887. break;
  86888. case TGATools._ORIGIN_UR:
  86889. x_start = header.width - 1;
  86890. x_step = -1;
  86891. x_end = -1;
  86892. y_start = 0;
  86893. y_step = 1;
  86894. y_end = header.height;
  86895. break;
  86896. case TGATools._ORIGIN_BR:
  86897. x_start = header.width - 1;
  86898. x_step = -1;
  86899. x_end = -1;
  86900. y_start = header.height - 1;
  86901. y_step = -1;
  86902. y_end = -1;
  86903. break;
  86904. }
  86905. // Load the specify method
  86906. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86907. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86908. var engine = texture.getEngine();
  86909. engine._uploadDataToTextureDirectly(texture, imageData);
  86910. };
  86911. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86912. var image = pixel_data, colormap = palettes;
  86913. var width = header.width, height = header.height;
  86914. var color, i = 0, x, y;
  86915. var imageData = new Uint8Array(width * height * 4);
  86916. for (y = y_start; y !== y_end; y += y_step) {
  86917. for (x = x_start; x !== x_end; x += x_step, i++) {
  86918. color = image[i];
  86919. imageData[(x + width * y) * 4 + 3] = 255;
  86920. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86921. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86922. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86923. }
  86924. }
  86925. return imageData;
  86926. };
  86927. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86928. var image = pixel_data;
  86929. var width = header.width, height = header.height;
  86930. var color, i = 0, x, y;
  86931. var imageData = new Uint8Array(width * height * 4);
  86932. for (y = y_start; y !== y_end; y += y_step) {
  86933. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86934. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86935. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86936. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86937. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86938. imageData[(x + width * y) * 4 + 0] = r;
  86939. imageData[(x + width * y) * 4 + 1] = g;
  86940. imageData[(x + width * y) * 4 + 2] = b;
  86941. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86942. }
  86943. }
  86944. return imageData;
  86945. };
  86946. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86947. var image = pixel_data;
  86948. var width = header.width, height = header.height;
  86949. var i = 0, x, y;
  86950. var imageData = new Uint8Array(width * height * 4);
  86951. for (y = y_start; y !== y_end; y += y_step) {
  86952. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86953. imageData[(x + width * y) * 4 + 3] = 255;
  86954. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86955. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86956. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86957. }
  86958. }
  86959. return imageData;
  86960. };
  86961. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86962. var image = pixel_data;
  86963. var width = header.width, height = header.height;
  86964. var i = 0, x, y;
  86965. var imageData = new Uint8Array(width * height * 4);
  86966. for (y = y_start; y !== y_end; y += y_step) {
  86967. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86968. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86969. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86970. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86971. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86972. }
  86973. }
  86974. return imageData;
  86975. };
  86976. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86977. var image = pixel_data;
  86978. var width = header.width, height = header.height;
  86979. var color, i = 0, x, y;
  86980. var imageData = new Uint8Array(width * height * 4);
  86981. for (y = y_start; y !== y_end; y += y_step) {
  86982. for (x = x_start; x !== x_end; x += x_step, i++) {
  86983. color = image[i];
  86984. imageData[(x + width * y) * 4 + 0] = color;
  86985. imageData[(x + width * y) * 4 + 1] = color;
  86986. imageData[(x + width * y) * 4 + 2] = color;
  86987. imageData[(x + width * y) * 4 + 3] = 255;
  86988. }
  86989. }
  86990. return imageData;
  86991. };
  86992. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86993. var image = pixel_data;
  86994. var width = header.width, height = header.height;
  86995. var i = 0, x, y;
  86996. var imageData = new Uint8Array(width * height * 4);
  86997. for (y = y_start; y !== y_end; y += y_step) {
  86998. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86999. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87000. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87001. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87002. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87003. }
  87004. }
  87005. return imageData;
  87006. };
  87007. //private static _TYPE_NO_DATA = 0;
  87008. TGATools._TYPE_INDEXED = 1;
  87009. TGATools._TYPE_RGB = 2;
  87010. TGATools._TYPE_GREY = 3;
  87011. TGATools._TYPE_RLE_INDEXED = 9;
  87012. TGATools._TYPE_RLE_RGB = 10;
  87013. TGATools._TYPE_RLE_GREY = 11;
  87014. TGATools._ORIGIN_MASK = 0x30;
  87015. TGATools._ORIGIN_SHIFT = 0x04;
  87016. TGATools._ORIGIN_BL = 0x00;
  87017. TGATools._ORIGIN_BR = 0x01;
  87018. TGATools._ORIGIN_UL = 0x02;
  87019. TGATools._ORIGIN_UR = 0x03;
  87020. return TGATools;
  87021. }());
  87022. BABYLON.TGATools = TGATools;
  87023. })(BABYLON || (BABYLON = {}));
  87024. //# sourceMappingURL=babylon.tga.js.map
  87025. var BABYLON;
  87026. (function (BABYLON) {
  87027. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87028. // All values and structures referenced from:
  87029. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87030. var DDS_MAGIC = 0x20534444;
  87031. var
  87032. //DDSD_CAPS = 0x1,
  87033. //DDSD_HEIGHT = 0x2,
  87034. //DDSD_WIDTH = 0x4,
  87035. //DDSD_PITCH = 0x8,
  87036. //DDSD_PIXELFORMAT = 0x1000,
  87037. DDSD_MIPMAPCOUNT = 0x20000;
  87038. //DDSD_LINEARSIZE = 0x80000,
  87039. //DDSD_DEPTH = 0x800000;
  87040. // var DDSCAPS_COMPLEX = 0x8,
  87041. // DDSCAPS_MIPMAP = 0x400000,
  87042. // DDSCAPS_TEXTURE = 0x1000;
  87043. var DDSCAPS2_CUBEMAP = 0x200;
  87044. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87045. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87046. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87047. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87048. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87049. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87050. // DDSCAPS2_VOLUME = 0x200000;
  87051. var
  87052. //DDPF_ALPHAPIXELS = 0x1,
  87053. //DDPF_ALPHA = 0x2,
  87054. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87055. //DDPF_YUV = 0x200,
  87056. DDPF_LUMINANCE = 0x20000;
  87057. function FourCCToInt32(value) {
  87058. return value.charCodeAt(0) +
  87059. (value.charCodeAt(1) << 8) +
  87060. (value.charCodeAt(2) << 16) +
  87061. (value.charCodeAt(3) << 24);
  87062. }
  87063. function Int32ToFourCC(value) {
  87064. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87065. }
  87066. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87067. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87068. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87069. var FOURCC_DX10 = FourCCToInt32("DX10");
  87070. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87071. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87072. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87073. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87074. var headerLengthInt = 31; // The header length in 32 bit ints
  87075. // Offsets into the header array
  87076. var off_magic = 0;
  87077. var off_size = 1;
  87078. var off_flags = 2;
  87079. var off_height = 3;
  87080. var off_width = 4;
  87081. var off_mipmapCount = 7;
  87082. var off_pfFlags = 20;
  87083. var off_pfFourCC = 21;
  87084. var off_RGBbpp = 22;
  87085. var off_RMask = 23;
  87086. var off_GMask = 24;
  87087. var off_BMask = 25;
  87088. var off_AMask = 26;
  87089. // var off_caps1 = 27;
  87090. var off_caps2 = 28;
  87091. // var off_caps3 = 29;
  87092. // var off_caps4 = 30;
  87093. var off_dxgiFormat = 32;
  87094. ;
  87095. var DDSTools = /** @class */ (function () {
  87096. function DDSTools() {
  87097. }
  87098. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87099. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87100. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87101. var mipmapCount = 1;
  87102. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87103. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87104. }
  87105. var fourCC = header[off_pfFourCC];
  87106. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87107. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87108. switch (fourCC) {
  87109. case FOURCC_D3DFMT_R16G16B16A16F:
  87110. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87111. break;
  87112. case FOURCC_D3DFMT_R32G32B32A32F:
  87113. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87114. break;
  87115. case FOURCC_DX10:
  87116. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87117. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87118. break;
  87119. }
  87120. }
  87121. return {
  87122. width: header[off_width],
  87123. height: header[off_height],
  87124. mipmapCount: mipmapCount,
  87125. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87126. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87127. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87128. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87129. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87130. dxgiFormat: dxgiFormat,
  87131. textureType: textureType
  87132. };
  87133. };
  87134. DDSTools._ToHalfFloat = function (value) {
  87135. if (!DDSTools._FloatView) {
  87136. DDSTools._FloatView = new Float32Array(1);
  87137. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87138. }
  87139. DDSTools._FloatView[0] = value;
  87140. var x = DDSTools._Int32View[0];
  87141. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87142. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87143. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87144. /* If zero, or denormal, or exponent underflows too much for a denormal
  87145. * half, return signed zero. */
  87146. if (e < 103) {
  87147. return bits;
  87148. }
  87149. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87150. if (e > 142) {
  87151. bits |= 0x7c00;
  87152. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87153. * not Inf, so make sure we set one mantissa bit too. */
  87154. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87155. return bits;
  87156. }
  87157. /* If exponent underflows but not too much, return a denormal */
  87158. if (e < 113) {
  87159. m |= 0x0800;
  87160. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87161. * to 1, which is OK. */
  87162. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87163. return bits;
  87164. }
  87165. bits |= ((e - 112) << 10) | (m >> 1);
  87166. bits += m & 1;
  87167. return bits;
  87168. };
  87169. DDSTools._FromHalfFloat = function (value) {
  87170. var s = (value & 0x8000) >> 15;
  87171. var e = (value & 0x7C00) >> 10;
  87172. var f = value & 0x03FF;
  87173. if (e === 0) {
  87174. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87175. }
  87176. else if (e == 0x1F) {
  87177. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87178. }
  87179. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87180. };
  87181. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87182. var destArray = new Float32Array(dataLength);
  87183. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87184. var index = 0;
  87185. for (var y = 0; y < height; y++) {
  87186. for (var x = 0; x < width; x++) {
  87187. var srcPos = (x + y * width) * 4;
  87188. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87189. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87190. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87191. if (DDSTools.StoreLODInAlphaChannel) {
  87192. destArray[index + 3] = lod;
  87193. }
  87194. else {
  87195. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87196. }
  87197. index += 4;
  87198. }
  87199. }
  87200. return destArray;
  87201. };
  87202. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87203. if (DDSTools.StoreLODInAlphaChannel) {
  87204. var destArray = new Uint16Array(dataLength);
  87205. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87206. var index = 0;
  87207. for (var y = 0; y < height; y++) {
  87208. for (var x = 0; x < width; x++) {
  87209. var srcPos = (x + y * width) * 4;
  87210. destArray[index] = srcData[srcPos];
  87211. destArray[index + 1] = srcData[srcPos + 1];
  87212. destArray[index + 2] = srcData[srcPos + 2];
  87213. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87214. index += 4;
  87215. }
  87216. }
  87217. return destArray;
  87218. }
  87219. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87220. };
  87221. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87222. if (DDSTools.StoreLODInAlphaChannel) {
  87223. var destArray = new Float32Array(dataLength);
  87224. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87225. var index = 0;
  87226. for (var y = 0; y < height; y++) {
  87227. for (var x = 0; x < width; x++) {
  87228. var srcPos = (x + y * width) * 4;
  87229. destArray[index] = srcData[srcPos];
  87230. destArray[index + 1] = srcData[srcPos + 1];
  87231. destArray[index + 2] = srcData[srcPos + 2];
  87232. destArray[index + 3] = lod;
  87233. index += 4;
  87234. }
  87235. }
  87236. return destArray;
  87237. }
  87238. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87239. };
  87240. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87241. var destArray = new Uint8Array(dataLength);
  87242. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87243. var index = 0;
  87244. for (var y = 0; y < height; y++) {
  87245. for (var x = 0; x < width; x++) {
  87246. var srcPos = (x + y * width) * 4;
  87247. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87248. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87249. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87250. if (DDSTools.StoreLODInAlphaChannel) {
  87251. destArray[index + 3] = lod;
  87252. }
  87253. else {
  87254. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87255. }
  87256. index += 4;
  87257. }
  87258. }
  87259. return destArray;
  87260. };
  87261. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87262. var destArray = new Uint8Array(dataLength);
  87263. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87264. var index = 0;
  87265. for (var y = 0; y < height; y++) {
  87266. for (var x = 0; x < width; x++) {
  87267. var srcPos = (x + y * width) * 4;
  87268. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87269. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87270. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87271. if (DDSTools.StoreLODInAlphaChannel) {
  87272. destArray[index + 3] = lod;
  87273. }
  87274. else {
  87275. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87276. }
  87277. index += 4;
  87278. }
  87279. }
  87280. return destArray;
  87281. };
  87282. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87283. var byteArray = new Uint8Array(dataLength);
  87284. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87285. var index = 0;
  87286. for (var y = 0; y < height; y++) {
  87287. for (var x = 0; x < width; x++) {
  87288. var srcPos = (x + y * width) * 4;
  87289. byteArray[index] = srcData[srcPos + rOffset];
  87290. byteArray[index + 1] = srcData[srcPos + gOffset];
  87291. byteArray[index + 2] = srcData[srcPos + bOffset];
  87292. byteArray[index + 3] = srcData[srcPos + aOffset];
  87293. index += 4;
  87294. }
  87295. }
  87296. return byteArray;
  87297. };
  87298. DDSTools._ExtractLongWordOrder = function (value) {
  87299. if (value === 0 || value === 255 || value === -16777216) {
  87300. return 0;
  87301. }
  87302. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87303. };
  87304. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87305. var byteArray = new Uint8Array(dataLength);
  87306. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87307. var index = 0;
  87308. for (var y = 0; y < height; y++) {
  87309. for (var x = 0; x < width; x++) {
  87310. var srcPos = (x + y * width) * 3;
  87311. byteArray[index] = srcData[srcPos + rOffset];
  87312. byteArray[index + 1] = srcData[srcPos + gOffset];
  87313. byteArray[index + 2] = srcData[srcPos + bOffset];
  87314. index += 3;
  87315. }
  87316. }
  87317. return byteArray;
  87318. };
  87319. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87320. var byteArray = new Uint8Array(dataLength);
  87321. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87322. var index = 0;
  87323. for (var y = 0; y < height; y++) {
  87324. for (var x = 0; x < width; x++) {
  87325. var srcPos = (x + y * width);
  87326. byteArray[index] = srcData[srcPos];
  87327. index++;
  87328. }
  87329. }
  87330. return byteArray;
  87331. };
  87332. /**
  87333. * Uploads DDS Levels to a Babylon Texture
  87334. * @hidden
  87335. */
  87336. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87337. if (lodIndex === void 0) { lodIndex = -1; }
  87338. var sphericalPolynomialFaces = null;
  87339. if (info.sphericalPolynomial) {
  87340. sphericalPolynomialFaces = new Array();
  87341. }
  87342. var ext = engine.getCaps().s3tc;
  87343. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87344. var fourCC, width, height, dataLength = 0, dataOffset;
  87345. var byteArray, mipmapCount, mip;
  87346. var internalCompressedFormat = 0;
  87347. var blockBytes = 1;
  87348. if (header[off_magic] !== DDS_MAGIC) {
  87349. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87350. return;
  87351. }
  87352. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87353. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87354. return;
  87355. }
  87356. if (info.isCompressed && !ext) {
  87357. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87358. return;
  87359. }
  87360. var bpp = header[off_RGBbpp];
  87361. dataOffset = header[off_size] + 4;
  87362. var computeFormats = false;
  87363. if (info.isFourCC) {
  87364. fourCC = header[off_pfFourCC];
  87365. switch (fourCC) {
  87366. case FOURCC_DXT1:
  87367. blockBytes = 8;
  87368. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87369. break;
  87370. case FOURCC_DXT3:
  87371. blockBytes = 16;
  87372. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87373. break;
  87374. case FOURCC_DXT5:
  87375. blockBytes = 16;
  87376. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87377. break;
  87378. case FOURCC_D3DFMT_R16G16B16A16F:
  87379. computeFormats = true;
  87380. break;
  87381. case FOURCC_D3DFMT_R32G32B32A32F:
  87382. computeFormats = true;
  87383. break;
  87384. case FOURCC_DX10:
  87385. // There is an additionnal header so dataOffset need to be changed
  87386. dataOffset += 5 * 4; // 5 uints
  87387. var supported = false;
  87388. switch (info.dxgiFormat) {
  87389. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87390. computeFormats = true;
  87391. supported = true;
  87392. break;
  87393. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87394. info.isRGB = true;
  87395. info.isFourCC = false;
  87396. bpp = 32;
  87397. supported = true;
  87398. break;
  87399. }
  87400. if (supported) {
  87401. break;
  87402. }
  87403. default:
  87404. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87405. return;
  87406. }
  87407. }
  87408. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87409. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87410. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87411. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87412. if (computeFormats) {
  87413. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87414. }
  87415. mipmapCount = 1;
  87416. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87417. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87418. }
  87419. for (var face = 0; face < faces; face++) {
  87420. width = header[off_width];
  87421. height = header[off_height];
  87422. for (mip = 0; mip < mipmapCount; ++mip) {
  87423. if (lodIndex === -1 || lodIndex === mip) {
  87424. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87425. var i = (lodIndex === -1) ? mip : 0;
  87426. if (!info.isCompressed && info.isFourCC) {
  87427. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87428. dataLength = width * height * 4;
  87429. var floatArray = null;
  87430. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87431. if (bpp === 128) {
  87432. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87433. if (sphericalPolynomialFaces && i == 0) {
  87434. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87435. }
  87436. }
  87437. else if (bpp === 64) {
  87438. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87439. if (sphericalPolynomialFaces && i == 0) {
  87440. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87441. }
  87442. }
  87443. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87444. }
  87445. else {
  87446. if (bpp === 128) {
  87447. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87448. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87449. if (sphericalPolynomialFaces && i == 0) {
  87450. sphericalPolynomialFaces.push(floatArray);
  87451. }
  87452. }
  87453. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87454. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87455. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87456. if (sphericalPolynomialFaces && i == 0) {
  87457. sphericalPolynomialFaces.push(floatArray);
  87458. }
  87459. }
  87460. else { // 64
  87461. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87462. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87463. if (sphericalPolynomialFaces && i == 0) {
  87464. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87465. }
  87466. }
  87467. }
  87468. if (floatArray) {
  87469. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87470. }
  87471. }
  87472. else if (info.isRGB) {
  87473. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87474. if (bpp === 24) {
  87475. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87476. dataLength = width * height * 3;
  87477. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87478. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87479. }
  87480. else { // 32
  87481. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87482. dataLength = width * height * 4;
  87483. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87484. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87485. }
  87486. }
  87487. else if (info.isLuminance) {
  87488. var unpackAlignment = engine._getUnpackAlignement();
  87489. var unpaddedRowSize = width;
  87490. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87491. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87492. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87493. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87494. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87495. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87496. }
  87497. else {
  87498. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87499. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87500. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87501. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87502. }
  87503. }
  87504. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87505. width *= 0.5;
  87506. height *= 0.5;
  87507. width = Math.max(1.0, width);
  87508. height = Math.max(1.0, height);
  87509. }
  87510. if (currentFace !== undefined) {
  87511. // Loading a single face
  87512. break;
  87513. }
  87514. }
  87515. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87516. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87517. size: header[off_width],
  87518. right: sphericalPolynomialFaces[0],
  87519. left: sphericalPolynomialFaces[1],
  87520. up: sphericalPolynomialFaces[2],
  87521. down: sphericalPolynomialFaces[3],
  87522. front: sphericalPolynomialFaces[4],
  87523. back: sphericalPolynomialFaces[5],
  87524. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87525. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87526. gammaSpace: false,
  87527. });
  87528. }
  87529. else {
  87530. info.sphericalPolynomial = undefined;
  87531. }
  87532. };
  87533. DDSTools.StoreLODInAlphaChannel = false;
  87534. return DDSTools;
  87535. }());
  87536. BABYLON.DDSTools = DDSTools;
  87537. })(BABYLON || (BABYLON = {}));
  87538. //# sourceMappingURL=babylon.dds.js.map
  87539. var BABYLON;
  87540. (function (BABYLON) {
  87541. /**
  87542. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87543. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87544. */
  87545. var KhronosTextureContainer = /** @class */ (function () {
  87546. /**
  87547. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87548. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87549. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87550. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87551. */
  87552. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87553. this.arrayBuffer = arrayBuffer;
  87554. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87555. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87556. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87557. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87558. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87559. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87560. BABYLON.Tools.Error("texture missing KTX identifier");
  87561. return;
  87562. }
  87563. // load the reset of the header in native 32 bit int
  87564. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87565. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87566. var oppositeEndianess = header[0] === 0x01020304;
  87567. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87568. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87569. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87570. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87571. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87572. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87573. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87574. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87575. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87576. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87577. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87578. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87579. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87580. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87581. if (this.glType !== 0) {
  87582. BABYLON.Tools.Error("only compressed formats currently supported");
  87583. return;
  87584. }
  87585. else {
  87586. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87587. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87588. }
  87589. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87590. BABYLON.Tools.Error("only 2D textures currently supported");
  87591. return;
  87592. }
  87593. if (this.numberOfArrayElements !== 0) {
  87594. BABYLON.Tools.Error("texture arrays not currently supported");
  87595. return;
  87596. }
  87597. if (this.numberOfFaces !== facesExpected) {
  87598. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87599. return;
  87600. }
  87601. // we now have a completely validated file, so could use existence of loadType as success
  87602. // would need to make this more elaborate & adjust checks above to support more than one load type
  87603. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87604. }
  87605. // not as fast hardware based, but will probably never need to use
  87606. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87607. return ((val & 0xFF) << 24)
  87608. | ((val & 0xFF00) << 8)
  87609. | ((val >> 8) & 0xFF00)
  87610. | ((val >> 24) & 0xFF);
  87611. };
  87612. /**
  87613. * Uploads KTX content to a Babylon Texture.
  87614. * It is assumed that the texture has already been created & is currently bound
  87615. * @hidden
  87616. */
  87617. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  87618. switch (this.loadType) {
  87619. case KhronosTextureContainer.COMPRESSED_2D:
  87620. this._upload2DCompressedLevels(texture, loadMipmaps);
  87621. break;
  87622. case KhronosTextureContainer.TEX_2D:
  87623. case KhronosTextureContainer.COMPRESSED_3D:
  87624. case KhronosTextureContainer.TEX_3D:
  87625. }
  87626. };
  87627. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  87628. // initialize width & height for level 1
  87629. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87630. var width = this.pixelWidth;
  87631. var height = this.pixelHeight;
  87632. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87633. for (var level = 0; level < mipmapCount; level++) {
  87634. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87635. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87636. for (var face = 0; face < this.numberOfFaces; face++) {
  87637. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87638. var engine = texture.getEngine();
  87639. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  87640. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87641. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87642. }
  87643. width = Math.max(1.0, width * 0.5);
  87644. height = Math.max(1.0, height * 0.5);
  87645. }
  87646. };
  87647. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87648. // load types
  87649. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87650. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87651. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87652. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87653. return KhronosTextureContainer;
  87654. }());
  87655. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87656. })(BABYLON || (BABYLON = {}));
  87657. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87658. var BABYLON;
  87659. (function (BABYLON) {
  87660. var Debug;
  87661. (function (Debug) {
  87662. /**
  87663. * Class used to render a debug view of a given skeleton
  87664. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87665. */
  87666. var SkeletonViewer = /** @class */ (function () {
  87667. /**
  87668. * Creates a new SkeletonViewer
  87669. * @param skeleton defines the skeleton to render
  87670. * @param mesh defines the mesh attached to the skeleton
  87671. * @param scene defines the hosting scene
  87672. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87673. * @param renderingGroupId defines the rendering group id to use with the viewer
  87674. */
  87675. function SkeletonViewer(
  87676. /** defines the skeleton to render */
  87677. skeleton,
  87678. /** defines the mesh attached to the skeleton */
  87679. mesh, scene,
  87680. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87681. autoUpdateBonesMatrices,
  87682. /** defines the rendering group id to use with the viewer */
  87683. renderingGroupId) {
  87684. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87685. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87686. this.skeleton = skeleton;
  87687. this.mesh = mesh;
  87688. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87689. this.renderingGroupId = renderingGroupId;
  87690. /** Gets or sets the color used to render the skeleton */
  87691. this.color = BABYLON.Color3.White();
  87692. this._debugLines = new Array();
  87693. this._isEnabled = false;
  87694. this._scene = scene;
  87695. this.update();
  87696. this._renderFunction = this.update.bind(this);
  87697. }
  87698. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87699. get: function () {
  87700. return this._isEnabled;
  87701. },
  87702. /** Gets or sets a boolean indicating if the viewer is enabled */
  87703. set: function (value) {
  87704. if (this._isEnabled === value) {
  87705. return;
  87706. }
  87707. this._isEnabled = value;
  87708. if (value) {
  87709. this._scene.registerBeforeRender(this._renderFunction);
  87710. }
  87711. else {
  87712. this._scene.unregisterBeforeRender(this._renderFunction);
  87713. }
  87714. },
  87715. enumerable: true,
  87716. configurable: true
  87717. });
  87718. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87719. if (x === void 0) { x = 0; }
  87720. if (y === void 0) { y = 0; }
  87721. if (z === void 0) { z = 0; }
  87722. var tmat = BABYLON.Tmp.Matrix[0];
  87723. var parentBone = bone.getParent();
  87724. tmat.copyFrom(bone.getLocalMatrix());
  87725. if (x !== 0 || y !== 0 || z !== 0) {
  87726. var tmat2 = BABYLON.Tmp.Matrix[1];
  87727. BABYLON.Matrix.IdentityToRef(tmat2);
  87728. tmat2.m[12] = x;
  87729. tmat2.m[13] = y;
  87730. tmat2.m[14] = z;
  87731. tmat2.multiplyToRef(tmat, tmat);
  87732. }
  87733. if (parentBone) {
  87734. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87735. }
  87736. tmat.multiplyToRef(meshMat, tmat);
  87737. position.x = tmat.m[12];
  87738. position.y = tmat.m[13];
  87739. position.z = tmat.m[14];
  87740. };
  87741. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87742. var len = bones.length;
  87743. var meshPos = this.mesh.position;
  87744. for (var i = 0; i < len; i++) {
  87745. var bone = bones[i];
  87746. var points = this._debugLines[i];
  87747. if (!points) {
  87748. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87749. this._debugLines[i] = points;
  87750. }
  87751. this._getBonePosition(points[0], bone, meshMat);
  87752. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87753. points[0].subtractInPlace(meshPos);
  87754. points[1].subtractInPlace(meshPos);
  87755. }
  87756. };
  87757. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87758. var len = bones.length;
  87759. var boneNum = 0;
  87760. var meshPos = this.mesh.position;
  87761. for (var i = len - 1; i >= 0; i--) {
  87762. var childBone = bones[i];
  87763. var parentBone = childBone.getParent();
  87764. if (!parentBone) {
  87765. continue;
  87766. }
  87767. var points = this._debugLines[boneNum];
  87768. if (!points) {
  87769. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87770. this._debugLines[boneNum] = points;
  87771. }
  87772. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87773. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87774. points[0].subtractInPlace(meshPos);
  87775. points[1].subtractInPlace(meshPos);
  87776. boneNum++;
  87777. }
  87778. };
  87779. /** Update the viewer to sync with current skeleton state */
  87780. SkeletonViewer.prototype.update = function () {
  87781. if (this.autoUpdateBonesMatrices) {
  87782. this.skeleton.computeAbsoluteTransforms();
  87783. }
  87784. if (this.skeleton.bones[0].length === undefined) {
  87785. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87786. }
  87787. else {
  87788. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87789. }
  87790. if (!this._debugMesh) {
  87791. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87792. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87793. }
  87794. else {
  87795. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87796. }
  87797. this._debugMesh.position.copyFrom(this.mesh.position);
  87798. this._debugMesh.color = this.color;
  87799. };
  87800. /** Release associated resources */
  87801. SkeletonViewer.prototype.dispose = function () {
  87802. if (this._debugMesh) {
  87803. this.isEnabled = false;
  87804. this._debugMesh.dispose();
  87805. this._debugMesh = null;
  87806. }
  87807. };
  87808. return SkeletonViewer;
  87809. }());
  87810. Debug.SkeletonViewer = SkeletonViewer;
  87811. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87812. })(BABYLON || (BABYLON = {}));
  87813. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87814. /**
  87815. * Module Debug contains the (visual) components to debug a scene correctly
  87816. */
  87817. var BABYLON;
  87818. (function (BABYLON) {
  87819. var Debug;
  87820. (function (Debug) {
  87821. /**
  87822. * The Axes viewer will show 3 axes in a specific point in space
  87823. */
  87824. var AxesViewer = /** @class */ (function () {
  87825. /**
  87826. * Creates a new AxesViewer
  87827. * @param scene defines the hosting scene
  87828. * @param scaleLines defines a number used to scale line length (1 by default)
  87829. */
  87830. function AxesViewer(scene, scaleLines) {
  87831. if (scaleLines === void 0) { scaleLines = 1; }
  87832. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87833. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87834. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87835. /**
  87836. * Gets or sets a number used to scale line length
  87837. */
  87838. this.scaleLines = 1;
  87839. this.scaleLines = scaleLines;
  87840. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87841. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87842. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87843. this._xmesh.renderingGroupId = 2;
  87844. this._ymesh.renderingGroupId = 2;
  87845. this._zmesh.renderingGroupId = 2;
  87846. this._xmesh.material.checkReadyOnlyOnce = true;
  87847. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87848. this._ymesh.material.checkReadyOnlyOnce = true;
  87849. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87850. this._zmesh.material.checkReadyOnlyOnce = true;
  87851. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87852. this.scene = scene;
  87853. }
  87854. /**
  87855. * Force the viewer to update
  87856. * @param position defines the position of the viewer
  87857. * @param xaxis defines the x axis of the viewer
  87858. * @param yaxis defines the y axis of the viewer
  87859. * @param zaxis defines the z axis of the viewer
  87860. */
  87861. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87862. var scaleLines = this.scaleLines;
  87863. if (this._xmesh) {
  87864. this._xmesh.position.copyFrom(position);
  87865. }
  87866. if (this._ymesh) {
  87867. this._ymesh.position.copyFrom(position);
  87868. }
  87869. if (this._zmesh) {
  87870. this._zmesh.position.copyFrom(position);
  87871. }
  87872. var point2 = this._xline[1];
  87873. point2.x = xaxis.x * scaleLines;
  87874. point2.y = xaxis.y * scaleLines;
  87875. point2.z = xaxis.z * scaleLines;
  87876. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87877. point2 = this._yline[1];
  87878. point2.x = yaxis.x * scaleLines;
  87879. point2.y = yaxis.y * scaleLines;
  87880. point2.z = yaxis.z * scaleLines;
  87881. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87882. point2 = this._zline[1];
  87883. point2.x = zaxis.x * scaleLines;
  87884. point2.y = zaxis.y * scaleLines;
  87885. point2.z = zaxis.z * scaleLines;
  87886. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87887. };
  87888. /** Releases resources */
  87889. AxesViewer.prototype.dispose = function () {
  87890. if (this._xmesh) {
  87891. this._xmesh.dispose();
  87892. }
  87893. if (this._ymesh) {
  87894. this._ymesh.dispose();
  87895. }
  87896. if (this._zmesh) {
  87897. this._zmesh.dispose();
  87898. }
  87899. this._xmesh = null;
  87900. this._ymesh = null;
  87901. this._zmesh = null;
  87902. this.scene = null;
  87903. };
  87904. return AxesViewer;
  87905. }());
  87906. Debug.AxesViewer = AxesViewer;
  87907. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87908. })(BABYLON || (BABYLON = {}));
  87909. //# sourceMappingURL=babylon.axesViewer.js.map
  87910. var BABYLON;
  87911. (function (BABYLON) {
  87912. var Debug;
  87913. (function (Debug) {
  87914. /**
  87915. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87916. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87917. */
  87918. var BoneAxesViewer = /** @class */ (function (_super) {
  87919. __extends(BoneAxesViewer, _super);
  87920. /**
  87921. * Creates a new BoneAxesViewer
  87922. * @param scene defines the hosting scene
  87923. * @param bone defines the target bone
  87924. * @param mesh defines the target mesh
  87925. * @param scaleLines defines a scaling factor for line length (1 by default)
  87926. */
  87927. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87928. if (scaleLines === void 0) { scaleLines = 1; }
  87929. var _this = _super.call(this, scene, scaleLines) || this;
  87930. /** Gets current position */
  87931. _this.pos = BABYLON.Vector3.Zero();
  87932. /** Gets direction of X axis */
  87933. _this.xaxis = BABYLON.Vector3.Zero();
  87934. /** Gets direction of Y axis */
  87935. _this.yaxis = BABYLON.Vector3.Zero();
  87936. /** Gets direction of Z axis */
  87937. _this.zaxis = BABYLON.Vector3.Zero();
  87938. _this.mesh = mesh;
  87939. _this.bone = bone;
  87940. return _this;
  87941. }
  87942. /**
  87943. * Force the viewer to update
  87944. */
  87945. BoneAxesViewer.prototype.update = function () {
  87946. if (!this.mesh || !this.bone) {
  87947. return;
  87948. }
  87949. var bone = this.bone;
  87950. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87951. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87952. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87953. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87954. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87955. };
  87956. /** Releases resources */
  87957. BoneAxesViewer.prototype.dispose = function () {
  87958. if (this.mesh) {
  87959. this.mesh = null;
  87960. this.bone = null;
  87961. _super.prototype.dispose.call(this);
  87962. }
  87963. };
  87964. return BoneAxesViewer;
  87965. }(Debug.AxesViewer));
  87966. Debug.BoneAxesViewer = BoneAxesViewer;
  87967. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87968. })(BABYLON || (BABYLON = {}));
  87969. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87970. var BABYLON;
  87971. (function (BABYLON) {
  87972. var RayHelper = /** @class */ (function () {
  87973. function RayHelper(ray) {
  87974. this.ray = ray;
  87975. }
  87976. RayHelper.CreateAndShow = function (ray, scene, color) {
  87977. var helper = new RayHelper(ray);
  87978. helper.show(scene, color);
  87979. return helper;
  87980. };
  87981. RayHelper.prototype.show = function (scene, color) {
  87982. if (!this._renderFunction && this.ray) {
  87983. var ray = this.ray;
  87984. this._renderFunction = this._render.bind(this);
  87985. this._scene = scene;
  87986. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87987. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87988. if (this._renderFunction) {
  87989. this._scene.registerBeforeRender(this._renderFunction);
  87990. }
  87991. }
  87992. if (color && this._renderLine) {
  87993. this._renderLine.color.copyFrom(color);
  87994. }
  87995. };
  87996. RayHelper.prototype.hide = function () {
  87997. if (this._renderFunction && this._scene) {
  87998. this._scene.unregisterBeforeRender(this._renderFunction);
  87999. this._scene = null;
  88000. this._renderFunction = null;
  88001. if (this._renderLine) {
  88002. this._renderLine.dispose();
  88003. this._renderLine = null;
  88004. }
  88005. this._renderPoints = [];
  88006. }
  88007. };
  88008. RayHelper.prototype._render = function () {
  88009. var ray = this.ray;
  88010. if (!ray) {
  88011. return;
  88012. }
  88013. var point = this._renderPoints[1];
  88014. var len = Math.min(ray.length, 1000000);
  88015. point.copyFrom(ray.direction);
  88016. point.scaleInPlace(len);
  88017. point.addInPlace(ray.origin);
  88018. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88019. };
  88020. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88021. this._attachedToMesh = mesh;
  88022. var ray = this.ray;
  88023. if (!ray) {
  88024. return;
  88025. }
  88026. if (!ray.direction) {
  88027. ray.direction = BABYLON.Vector3.Zero();
  88028. }
  88029. if (!ray.origin) {
  88030. ray.origin = BABYLON.Vector3.Zero();
  88031. }
  88032. if (length) {
  88033. ray.length = length;
  88034. }
  88035. if (!meshSpaceOrigin) {
  88036. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88037. }
  88038. if (!meshSpaceDirection) {
  88039. // -1 so that this will work with Mesh.lookAt
  88040. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88041. }
  88042. if (!this._meshSpaceDirection) {
  88043. this._meshSpaceDirection = meshSpaceDirection.clone();
  88044. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88045. }
  88046. else {
  88047. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88048. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88049. }
  88050. if (!this._updateToMeshFunction) {
  88051. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88052. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88053. }
  88054. this._updateToMesh();
  88055. };
  88056. RayHelper.prototype.detachFromMesh = function () {
  88057. if (this._attachedToMesh) {
  88058. if (this._updateToMeshFunction) {
  88059. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88060. }
  88061. this._attachedToMesh = null;
  88062. this._updateToMeshFunction = null;
  88063. }
  88064. };
  88065. RayHelper.prototype._updateToMesh = function () {
  88066. var ray = this.ray;
  88067. if (!this._attachedToMesh || !ray) {
  88068. return;
  88069. }
  88070. if (this._attachedToMesh._isDisposed) {
  88071. this.detachFromMesh();
  88072. return;
  88073. }
  88074. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88075. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88076. };
  88077. RayHelper.prototype.dispose = function () {
  88078. this.hide();
  88079. this.detachFromMesh();
  88080. this.ray = null;
  88081. };
  88082. return RayHelper;
  88083. }());
  88084. BABYLON.RayHelper = RayHelper;
  88085. })(BABYLON || (BABYLON = {}));
  88086. //# sourceMappingURL=babylon.rayHelper.js.map
  88087. var BABYLON;
  88088. (function (BABYLON) {
  88089. // load the inspector using require, if not present in the global namespace.
  88090. var DebugLayer = /** @class */ (function () {
  88091. function DebugLayer(scene) {
  88092. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88093. this.onPropertyChangedObservable = new BABYLON.Observable();
  88094. this._scene = scene;
  88095. }
  88096. /** Creates the inspector window. */
  88097. DebugLayer.prototype._createInspector = function (config) {
  88098. if (config === void 0) { config = {}; }
  88099. var popup = config.popup || false;
  88100. var initialTab = config.initialTab || 0;
  88101. var parentElement = config.parentElement || null;
  88102. if (!this._inspector) {
  88103. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88104. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88105. } // else nothing to do as instance is already created
  88106. };
  88107. DebugLayer.prototype.isVisible = function () {
  88108. if (!this._inspector) {
  88109. return false;
  88110. }
  88111. return true;
  88112. };
  88113. DebugLayer.prototype.hide = function () {
  88114. if (this._inspector) {
  88115. try {
  88116. this._inspector.dispose();
  88117. }
  88118. catch (e) {
  88119. // If the inspector has been removed directly from the inspector tool
  88120. }
  88121. this.onPropertyChangedObservable.clear();
  88122. this._inspector = null;
  88123. }
  88124. };
  88125. /**
  88126. *
  88127. * Launch the debugLayer.
  88128. *
  88129. * initialTab:
  88130. * | Value | Tab Name |
  88131. * | --- | --- |
  88132. * | 0 | Scene |
  88133. * | 1 | Console |
  88134. * | 2 | Stats |
  88135. * | 3 | Textures |
  88136. * | 4 | Mesh |
  88137. * | 5 | Light |
  88138. * | 6 | Material |
  88139. * | 7 | GLTF |
  88140. * | 8 | GUI |
  88141. * | 9 | Physics |
  88142. * | 10 | Camera |
  88143. * | 11 | Audio |
  88144. *
  88145. */
  88146. DebugLayer.prototype.show = function (config) {
  88147. if (config === void 0) { config = {}; }
  88148. if (typeof this.BJSINSPECTOR == 'undefined') {
  88149. // Load inspector and add it to the DOM
  88150. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88151. }
  88152. else {
  88153. // Otherwise creates the inspector
  88154. this._createInspector(config);
  88155. }
  88156. };
  88157. /**
  88158. * Gets the active tab
  88159. * @return the index of the active tab or -1 if the inspector is hidden
  88160. */
  88161. DebugLayer.prototype.getActiveTab = function () {
  88162. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88163. };
  88164. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88165. return DebugLayer;
  88166. }());
  88167. BABYLON.DebugLayer = DebugLayer;
  88168. })(BABYLON || (BABYLON = {}));
  88169. //# sourceMappingURL=babylon.debugLayer.js.map
  88170. var BABYLON;
  88171. (function (BABYLON) {
  88172. var Debug;
  88173. (function (Debug) {
  88174. /**
  88175. * Used to show the physics impostor around the specific mesh
  88176. */
  88177. var PhysicsViewer = /** @class */ (function () {
  88178. /**
  88179. * Creates a new PhysicsViewer
  88180. * @param scene defines the hosting scene
  88181. */
  88182. function PhysicsViewer(scene) {
  88183. /** @hidden */
  88184. this._impostors = [];
  88185. /** @hidden */
  88186. this._meshes = [];
  88187. /** @hidden */
  88188. this._numMeshes = 0;
  88189. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88190. var physicEngine = this._scene.getPhysicsEngine();
  88191. if (physicEngine) {
  88192. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88193. }
  88194. }
  88195. /** @hidden */
  88196. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88197. var plugin = this._physicsEnginePlugin;
  88198. for (var i = 0; i < this._numMeshes; i++) {
  88199. var impostor = this._impostors[i];
  88200. if (!impostor) {
  88201. continue;
  88202. }
  88203. if (impostor.isDisposed) {
  88204. this.hideImpostor(this._impostors[i--]);
  88205. }
  88206. else {
  88207. var mesh = this._meshes[i];
  88208. if (mesh && plugin) {
  88209. plugin.syncMeshWithImpostor(mesh, impostor);
  88210. }
  88211. }
  88212. }
  88213. };
  88214. /**
  88215. * Renders a specified physic impostor
  88216. * @param impostor defines the impostor to render
  88217. */
  88218. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88219. if (!this._scene) {
  88220. return;
  88221. }
  88222. for (var i = 0; i < this._numMeshes; i++) {
  88223. if (this._impostors[i] == impostor) {
  88224. return;
  88225. }
  88226. }
  88227. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88228. if (debugMesh) {
  88229. this._impostors[this._numMeshes] = impostor;
  88230. this._meshes[this._numMeshes] = debugMesh;
  88231. if (this._numMeshes === 0) {
  88232. this._renderFunction = this._updateDebugMeshes.bind(this);
  88233. this._scene.registerBeforeRender(this._renderFunction);
  88234. }
  88235. this._numMeshes++;
  88236. }
  88237. };
  88238. /**
  88239. * Hides a specified physic impostor
  88240. * @param impostor defines the impostor to hide
  88241. */
  88242. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88243. if (!impostor || !this._scene) {
  88244. return;
  88245. }
  88246. var removed = false;
  88247. for (var i = 0; i < this._numMeshes; i++) {
  88248. if (this._impostors[i] == impostor) {
  88249. var mesh = this._meshes[i];
  88250. if (!mesh) {
  88251. continue;
  88252. }
  88253. this._scene.removeMesh(mesh);
  88254. mesh.dispose();
  88255. this._numMeshes--;
  88256. if (this._numMeshes > 0) {
  88257. this._meshes[i] = this._meshes[this._numMeshes];
  88258. this._impostors[i] = this._impostors[this._numMeshes];
  88259. this._meshes[this._numMeshes] = null;
  88260. this._impostors[this._numMeshes] = null;
  88261. }
  88262. else {
  88263. this._meshes[0] = null;
  88264. this._impostors[0] = null;
  88265. }
  88266. removed = true;
  88267. break;
  88268. }
  88269. }
  88270. if (removed && this._numMeshes === 0) {
  88271. this._scene.unregisterBeforeRender(this._renderFunction);
  88272. }
  88273. };
  88274. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88275. if (!this._debugMaterial) {
  88276. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88277. this._debugMaterial.wireframe = true;
  88278. }
  88279. return this._debugMaterial;
  88280. };
  88281. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88282. if (!this._debugBoxMesh) {
  88283. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88284. this._debugBoxMesh.renderingGroupId = 1;
  88285. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88286. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88287. scene.removeMesh(this._debugBoxMesh);
  88288. }
  88289. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88290. };
  88291. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88292. if (!this._debugSphereMesh) {
  88293. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88294. this._debugSphereMesh.renderingGroupId = 1;
  88295. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88296. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88297. scene.removeMesh(this._debugSphereMesh);
  88298. }
  88299. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88300. };
  88301. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88302. var mesh = null;
  88303. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88304. mesh = this._getDebugBoxMesh(scene);
  88305. impostor.getBoxSizeToRef(mesh.scaling);
  88306. }
  88307. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88308. mesh = this._getDebugSphereMesh(scene);
  88309. var radius = impostor.getRadius();
  88310. mesh.scaling.x = radius * 2;
  88311. mesh.scaling.y = radius * 2;
  88312. mesh.scaling.z = radius * 2;
  88313. }
  88314. return mesh;
  88315. };
  88316. /** Releases all resources */
  88317. PhysicsViewer.prototype.dispose = function () {
  88318. for (var i = 0; i < this._numMeshes; i++) {
  88319. this.hideImpostor(this._impostors[i]);
  88320. }
  88321. if (this._debugBoxMesh) {
  88322. this._debugBoxMesh.dispose();
  88323. }
  88324. if (this._debugSphereMesh) {
  88325. this._debugSphereMesh.dispose();
  88326. }
  88327. if (this._debugMaterial) {
  88328. this._debugMaterial.dispose();
  88329. }
  88330. this._impostors.length = 0;
  88331. this._scene = null;
  88332. this._physicsEnginePlugin = null;
  88333. };
  88334. return PhysicsViewer;
  88335. }());
  88336. Debug.PhysicsViewer = PhysicsViewer;
  88337. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88338. })(BABYLON || (BABYLON = {}));
  88339. //# sourceMappingURL=babylon.physicsViewer.js.map
  88340. var BABYLON;
  88341. (function (BABYLON) {
  88342. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  88343. get: function () {
  88344. return this._forceShowBoundingBoxes || false;
  88345. },
  88346. set: function (value) {
  88347. this._forceShowBoundingBoxes = value;
  88348. // Lazyly creates a BB renderer if needed.
  88349. if (value) {
  88350. this.getBoundingBoxRenderer();
  88351. }
  88352. },
  88353. enumerable: true,
  88354. configurable: true
  88355. });
  88356. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  88357. if (!this._boundingBoxRenderer) {
  88358. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  88359. }
  88360. return this._boundingBoxRenderer;
  88361. };
  88362. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  88363. get: function () {
  88364. return this._showBoundingBox || false;
  88365. },
  88366. set: function (value) {
  88367. this._showBoundingBox = value;
  88368. // Lazyly creates a BB renderer if needed.
  88369. if (value) {
  88370. this.getScene().getBoundingBoxRenderer();
  88371. }
  88372. },
  88373. enumerable: true,
  88374. configurable: true
  88375. });
  88376. var BoundingBoxRenderer = /** @class */ (function () {
  88377. function BoundingBoxRenderer(scene) {
  88378. /**
  88379. * The component name helpfull to identify the component in the list of scene components.
  88380. */
  88381. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  88382. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88383. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88384. this.showBackLines = true;
  88385. this.renderList = new BABYLON.SmartArray(32);
  88386. this._vertexBuffers = {};
  88387. this.scene = scene;
  88388. scene._addComponent(this);
  88389. }
  88390. /**
  88391. * Registers the component in a given scene
  88392. */
  88393. BoundingBoxRenderer.prototype.register = function () {
  88394. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  88395. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  88396. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  88397. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  88398. };
  88399. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  88400. if (mesh.showSubMeshesBoundingBox) {
  88401. var boundingInfo = subMesh.getBoundingInfo();
  88402. if (boundingInfo !== null && boundingInfo !== undefined) {
  88403. this.renderList.push(boundingInfo.boundingBox);
  88404. }
  88405. }
  88406. };
  88407. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  88408. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  88409. var boundingInfo = sourceMesh.getBoundingInfo();
  88410. this.renderList.push(boundingInfo.boundingBox);
  88411. }
  88412. };
  88413. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88414. if (this._colorShader) {
  88415. return;
  88416. }
  88417. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  88418. attributes: [BABYLON.VertexBuffer.PositionKind],
  88419. uniforms: ["world", "viewProjection", "color"]
  88420. });
  88421. var engine = this.scene.getEngine();
  88422. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88423. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88424. this._createIndexBuffer();
  88425. };
  88426. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88427. var engine = this.scene.getEngine();
  88428. 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]);
  88429. };
  88430. /**
  88431. * Rebuilds the elements related to this component in case of
  88432. * context lost for instance.
  88433. */
  88434. BoundingBoxRenderer.prototype.rebuild = function () {
  88435. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88436. if (vb) {
  88437. vb._rebuild();
  88438. }
  88439. this._createIndexBuffer();
  88440. };
  88441. BoundingBoxRenderer.prototype.reset = function () {
  88442. this.renderList.reset();
  88443. };
  88444. BoundingBoxRenderer.prototype.render = function () {
  88445. if (this.renderList.length === 0) {
  88446. return;
  88447. }
  88448. this._prepareRessources();
  88449. if (!this._colorShader.isReady()) {
  88450. return;
  88451. }
  88452. var engine = this.scene.getEngine();
  88453. engine.setDepthWrite(false);
  88454. this._colorShader._preBind();
  88455. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88456. var boundingBox = this.renderList.data[boundingBoxIndex];
  88457. var min = boundingBox.minimum;
  88458. var max = boundingBox.maximum;
  88459. var diff = max.subtract(min);
  88460. var median = min.add(diff.scale(0.5));
  88461. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88462. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88463. .multiply(boundingBox.getWorldMatrix());
  88464. // VBOs
  88465. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88466. if (this.showBackLines) {
  88467. // Back
  88468. engine.setDepthFunctionToGreaterOrEqual();
  88469. this.scene.resetCachedMaterial();
  88470. this._colorShader.setColor4("color", this.backColor.toColor4());
  88471. this._colorShader.bind(worldMatrix);
  88472. // Draw order
  88473. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88474. }
  88475. // Front
  88476. engine.setDepthFunctionToLess();
  88477. this.scene.resetCachedMaterial();
  88478. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88479. this._colorShader.bind(worldMatrix);
  88480. // Draw order
  88481. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88482. }
  88483. this._colorShader.unbind();
  88484. engine.setDepthFunctionToLessOrEqual();
  88485. engine.setDepthWrite(true);
  88486. };
  88487. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88488. this._prepareRessources();
  88489. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88490. return;
  88491. }
  88492. var engine = this.scene.getEngine();
  88493. engine.setDepthWrite(false);
  88494. engine.setColorWrite(false);
  88495. this._colorShader._preBind();
  88496. var boundingBox = mesh._boundingInfo.boundingBox;
  88497. var min = boundingBox.minimum;
  88498. var max = boundingBox.maximum;
  88499. var diff = max.subtract(min);
  88500. var median = min.add(diff.scale(0.5));
  88501. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88502. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88503. .multiply(boundingBox.getWorldMatrix());
  88504. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88505. engine.setDepthFunctionToLess();
  88506. this.scene.resetCachedMaterial();
  88507. this._colorShader.bind(worldMatrix);
  88508. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88509. this._colorShader.unbind();
  88510. engine.setDepthFunctionToLessOrEqual();
  88511. engine.setDepthWrite(true);
  88512. engine.setColorWrite(true);
  88513. };
  88514. BoundingBoxRenderer.prototype.dispose = function () {
  88515. if (!this._colorShader) {
  88516. return;
  88517. }
  88518. this.renderList.dispose();
  88519. this._colorShader.dispose();
  88520. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88521. if (buffer) {
  88522. buffer.dispose();
  88523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88524. }
  88525. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  88526. };
  88527. return BoundingBoxRenderer;
  88528. }());
  88529. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88530. })(BABYLON || (BABYLON = {}));
  88531. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88532. var BABYLON;
  88533. (function (BABYLON) {
  88534. /**
  88535. * Renders a layer on top of an existing scene
  88536. */
  88537. var UtilityLayerRenderer = /** @class */ (function () {
  88538. /**
  88539. * Instantiates a UtilityLayerRenderer
  88540. * @param originalScene the original scene that will be rendered on top of
  88541. */
  88542. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88543. var _this = this;
  88544. this.originalScene = originalScene;
  88545. this._pointerCaptures = {};
  88546. this._lastPointerEvents = {};
  88547. /**
  88548. * If the utility layer should automatically be rendered on top of existing scene
  88549. */
  88550. this.shouldRender = true;
  88551. /**
  88552. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88553. */
  88554. this.onlyCheckPointerDownEvents = true;
  88555. /**
  88556. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88557. */
  88558. this.processAllEvents = false;
  88559. /**
  88560. * Observable raised when the pointer move from the utility layer scene to the main scene
  88561. */
  88562. this.onPointerOutObservable = new BABYLON.Observable();
  88563. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88564. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88565. originalScene.getEngine().scenes.pop();
  88566. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88567. this.utilityLayerScene.detachControl();
  88568. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88569. if (!_this.processAllEvents) {
  88570. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88571. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88572. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88573. return;
  88574. }
  88575. }
  88576. var pointerEvent = (prePointerInfo.event);
  88577. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88578. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88579. return;
  88580. }
  88581. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88582. if (!prePointerInfo.ray && utilityScenePick) {
  88583. prePointerInfo.ray = utilityScenePick.ray;
  88584. }
  88585. // always fire the prepointer oversvable
  88586. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88587. // allow every non pointer down event to flow to the utility layer
  88588. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88589. if (!prePointerInfo.skipOnPointerObservable) {
  88590. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88591. }
  88592. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88593. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88594. }
  88595. return;
  88596. }
  88597. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88598. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88599. if (utilityScenePick && utilityScenePick.hit) {
  88600. if (!prePointerInfo.skipOnPointerObservable) {
  88601. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88602. }
  88603. prePointerInfo.skipOnPointerObservable = true;
  88604. }
  88605. }
  88606. else {
  88607. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88608. var pointerEvent_1 = (prePointerInfo.event);
  88609. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88610. if (originalScenePick && utilityScenePick) {
  88611. // No pick in utility scene
  88612. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88613. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88614. // We touched an utility mesh present in the main scene
  88615. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88616. prePointerInfo.skipOnPointerObservable = true;
  88617. }
  88618. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88619. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88620. }
  88621. }
  88622. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88623. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88624. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88625. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88626. }
  88627. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88628. // We have a pick in both scenes but main is closer than utility
  88629. // We touched an utility mesh present in the main scene
  88630. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88631. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88632. prePointerInfo.skipOnPointerObservable = true;
  88633. }
  88634. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88635. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88636. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88637. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88638. }
  88639. }
  88640. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88641. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88642. }
  88643. }
  88644. }
  88645. });
  88646. // Render directly on top of existing scene without clearing
  88647. this.utilityLayerScene.autoClear = false;
  88648. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88649. if (_this.shouldRender) {
  88650. _this.render();
  88651. }
  88652. });
  88653. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88654. _this.dispose();
  88655. });
  88656. this._updateCamera();
  88657. }
  88658. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88659. get: function () {
  88660. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88661. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88662. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88663. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88664. });
  88665. }
  88666. return UtilityLayerRenderer._DefaultUtilityLayer;
  88667. },
  88668. enumerable: true,
  88669. configurable: true
  88670. });
  88671. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88672. if (!prePointerInfo.skipOnPointerObservable) {
  88673. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88674. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88675. }
  88676. };
  88677. /**
  88678. * Renders the utility layers scene on top of the original scene
  88679. */
  88680. UtilityLayerRenderer.prototype.render = function () {
  88681. this._updateCamera();
  88682. this.utilityLayerScene.render(false);
  88683. };
  88684. /**
  88685. * Disposes of the renderer
  88686. */
  88687. UtilityLayerRenderer.prototype.dispose = function () {
  88688. this.onPointerOutObservable.clear();
  88689. if (this._afterRenderObserver) {
  88690. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88691. }
  88692. if (this._sceneDisposeObserver) {
  88693. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88694. }
  88695. if (this._originalPointerObserver) {
  88696. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88697. }
  88698. this.utilityLayerScene.dispose();
  88699. };
  88700. UtilityLayerRenderer.prototype._updateCamera = function () {
  88701. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88702. };
  88703. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88704. return UtilityLayerRenderer;
  88705. }());
  88706. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88707. })(BABYLON || (BABYLON = {}));
  88708. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88709. //# sourceMappingURL=babylon.behavior.js.map
  88710. var BABYLON;
  88711. (function (BABYLON) {
  88712. /**
  88713. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88714. */
  88715. var PointerDragBehavior = /** @class */ (function () {
  88716. /**
  88717. * Creates a pointer drag behavior that can be attached to a mesh
  88718. * @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)
  88719. */
  88720. function PointerDragBehavior(options) {
  88721. /**
  88722. * 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)
  88723. */
  88724. this.maxDragAngle = 0;
  88725. /**
  88726. * @hidden
  88727. */
  88728. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88729. /**
  88730. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88731. */
  88732. this.currentDraggingPointerID = -1;
  88733. /**
  88734. * If the behavior is currently in a dragging state
  88735. */
  88736. this.dragging = false;
  88737. /**
  88738. * 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)
  88739. */
  88740. this.dragDeltaRatio = 0.2;
  88741. /**
  88742. * If the drag plane orientation should be updated during the dragging (Default: true)
  88743. */
  88744. this.updateDragPlane = true;
  88745. // Debug mode will display drag planes to help visualize behavior
  88746. this._debugMode = false;
  88747. this._moving = false;
  88748. /**
  88749. * Fires each time the attached mesh is dragged with the pointer
  88750. * * delta between last drag position and current drag position in world space
  88751. * * dragDistance along the drag axis
  88752. * * dragPlaneNormal normal of the current drag plane used during the drag
  88753. * * dragPlanePoint in world space where the drag intersects the drag plane
  88754. */
  88755. this.onDragObservable = new BABYLON.Observable();
  88756. /**
  88757. * Fires each time a drag begins (eg. mouse down on mesh)
  88758. */
  88759. this.onDragStartObservable = new BABYLON.Observable();
  88760. /**
  88761. * Fires each time a drag ends (eg. mouse release after drag)
  88762. */
  88763. this.onDragEndObservable = new BABYLON.Observable();
  88764. /**
  88765. * If the attached mesh should be moved when dragged
  88766. */
  88767. this.moveAttached = true;
  88768. /**
  88769. * If the drag behavior will react to drag events (Default: true)
  88770. */
  88771. this.enabled = true;
  88772. /**
  88773. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88774. */
  88775. this.useObjectOrienationForDragging = true;
  88776. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88777. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88778. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88779. // Variables to avoid instantiation in the below method
  88780. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88781. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88782. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88783. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88784. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88785. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88786. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88787. this._options = options ? options : {};
  88788. var optionCount = 0;
  88789. if (this._options.dragAxis) {
  88790. optionCount++;
  88791. }
  88792. if (this._options.dragPlaneNormal) {
  88793. optionCount++;
  88794. }
  88795. if (optionCount > 1) {
  88796. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88797. }
  88798. }
  88799. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88800. /**
  88801. * The name of the behavior
  88802. */
  88803. get: function () {
  88804. return "PointerDrag";
  88805. },
  88806. enumerable: true,
  88807. configurable: true
  88808. });
  88809. /**
  88810. * Initializes the behavior
  88811. */
  88812. PointerDragBehavior.prototype.init = function () { };
  88813. /**
  88814. * Attaches the drag behavior the passed in mesh
  88815. * @param ownerNode The mesh that will be dragged around once attached
  88816. */
  88817. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88818. var _this = this;
  88819. this._scene = ownerNode.getScene();
  88820. this._attachedNode = ownerNode;
  88821. // Initialize drag plane to not interfere with existing scene
  88822. if (!PointerDragBehavior._planeScene) {
  88823. if (this._debugMode) {
  88824. PointerDragBehavior._planeScene = this._scene;
  88825. }
  88826. else {
  88827. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88828. this._scene.getEngine().scenes.pop();
  88829. }
  88830. }
  88831. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88832. // State of the drag
  88833. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88834. var delta = new BABYLON.Vector3(0, 0, 0);
  88835. var dragLength = 0;
  88836. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88837. var pickPredicate = function (m) {
  88838. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88839. };
  88840. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88841. if (!_this.enabled) {
  88842. return;
  88843. }
  88844. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88845. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88846. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88847. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88848. if (pickedPoint) {
  88849. _this.dragging = true;
  88850. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88851. _this.lastDragPosition.copyFrom(pickedPoint);
  88852. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88853. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88854. }
  88855. }
  88856. }
  88857. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88858. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88859. _this.releaseDrag();
  88860. }
  88861. }
  88862. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88863. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88864. _this._moving = true;
  88865. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88866. if (pickedPoint) {
  88867. if (_this.updateDragPlane) {
  88868. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88869. }
  88870. // depending on the drag mode option drag accordingly
  88871. if (_this._options.dragAxis) {
  88872. // Convert local drag axis to world
  88873. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88874. // Project delta drag from the drag plane onto the drag axis
  88875. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88876. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88877. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88878. }
  88879. else {
  88880. dragLength = delta.length();
  88881. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88882. }
  88883. targetPosition.addInPlace(delta);
  88884. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88885. _this.lastDragPosition.copyFrom(pickedPoint);
  88886. }
  88887. }
  88888. }
  88889. });
  88890. this._scene.onBeforeRenderObservable.add(function () {
  88891. if (_this._moving && _this.moveAttached) {
  88892. // Slowly move mesh to avoid jitter
  88893. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88894. _this._tmpVector.scaleInPlace(0.2);
  88895. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88896. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88897. }
  88898. });
  88899. };
  88900. PointerDragBehavior.prototype.releaseDrag = function () {
  88901. this.dragging = false;
  88902. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88903. this.currentDraggingPointerID = -1;
  88904. this._moving = false;
  88905. };
  88906. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88907. var _this = this;
  88908. if (!ray) {
  88909. return null;
  88910. }
  88911. // Calculate angle between plane normal and ray
  88912. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  88913. // Correct if ray is casted from oposite side
  88914. if (angle > Math.PI / 2) {
  88915. angle = Math.PI - angle;
  88916. }
  88917. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  88918. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  88919. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  88920. // Invert ray direction along the towards object axis
  88921. this._tmpVector.copyFrom(ray.direction);
  88922. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  88923. this._alternatePickedPoint.normalize();
  88924. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  88925. this._tmpVector.addInPlace(this._alternatePickedPoint);
  88926. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  88927. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  88928. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  88929. this._alternatePickedPoint.addInPlace(this._tmpVector);
  88930. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  88931. return this._alternatePickedPoint;
  88932. }
  88933. else {
  88934. return null;
  88935. }
  88936. }
  88937. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88938. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88939. return pickResult.pickedPoint;
  88940. }
  88941. else {
  88942. return null;
  88943. }
  88944. };
  88945. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88946. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88947. this._pointA.copyFrom(dragPlanePosition);
  88948. if (this._options.dragAxis) {
  88949. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  88950. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88951. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88952. ray.origin.subtractToRef(this._pointA, this._pointC);
  88953. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88954. // Get perpendicular line from direction to camera and drag axis
  88955. this._pointB.subtractToRef(this._pointA, this._lineA);
  88956. this._pointC.subtractToRef(this._pointA, this._lineB);
  88957. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88958. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88959. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88960. this._lookAt.normalize();
  88961. this._dragPlane.position.copyFrom(this._pointA);
  88962. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88963. this._dragPlane.lookAt(this._lookAt);
  88964. }
  88965. else if (this._options.dragPlaneNormal) {
  88966. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  88967. this._dragPlane.position.copyFrom(this._pointA);
  88968. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88969. this._dragPlane.lookAt(this._lookAt);
  88970. }
  88971. else {
  88972. this._dragPlane.position.copyFrom(this._pointA);
  88973. this._dragPlane.lookAt(ray.origin);
  88974. }
  88975. this._dragPlane.computeWorldMatrix(true);
  88976. };
  88977. /**
  88978. * Detaches the behavior from the mesh
  88979. */
  88980. PointerDragBehavior.prototype.detach = function () {
  88981. if (this._pointerObserver) {
  88982. this._scene.onPointerObservable.remove(this._pointerObserver);
  88983. }
  88984. };
  88985. return PointerDragBehavior;
  88986. }());
  88987. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88988. })(BABYLON || (BABYLON = {}));
  88989. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88990. var BABYLON;
  88991. (function (BABYLON) {
  88992. /**
  88993. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88994. */
  88995. var MultiPointerScaleBehavior = /** @class */ (function () {
  88996. function MultiPointerScaleBehavior() {
  88997. this._startDistance = 0;
  88998. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88999. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89000. this._sceneRenderObserver = null;
  89001. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89002. this._dragBehaviorA.moveAttached = false;
  89003. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89004. this._dragBehaviorB.moveAttached = false;
  89005. }
  89006. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89007. /**
  89008. * The name of the behavior
  89009. */
  89010. get: function () {
  89011. return "MultiPointerScale";
  89012. },
  89013. enumerable: true,
  89014. configurable: true
  89015. });
  89016. /**
  89017. * Initializes the behavior
  89018. */
  89019. MultiPointerScaleBehavior.prototype.init = function () { };
  89020. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89021. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89022. };
  89023. /**
  89024. * Attaches the scale behavior the passed in mesh
  89025. * @param ownerNode The mesh that will be scaled around once attached
  89026. */
  89027. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89028. var _this = this;
  89029. this._ownerNode = ownerNode;
  89030. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89031. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89032. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89033. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89034. _this._dragBehaviorA.releaseDrag();
  89035. }
  89036. else {
  89037. _this._initialScale.copyFrom(ownerNode.scaling);
  89038. _this._startDistance = _this._getCurrentDistance();
  89039. }
  89040. }
  89041. });
  89042. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89043. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89044. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89045. _this._dragBehaviorB.releaseDrag();
  89046. }
  89047. else {
  89048. _this._initialScale.copyFrom(ownerNode.scaling);
  89049. _this._startDistance = _this._getCurrentDistance();
  89050. }
  89051. }
  89052. });
  89053. // Once both drag behaviors are active scale based on the distance between the two pointers
  89054. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89055. behavior.onDragObservable.add(function () {
  89056. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89057. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89058. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89059. }
  89060. });
  89061. });
  89062. ownerNode.addBehavior(this._dragBehaviorA);
  89063. ownerNode.addBehavior(this._dragBehaviorB);
  89064. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89065. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89066. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89067. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89068. if (change.length() > 0.01) {
  89069. ownerNode.scaling.addInPlace(change);
  89070. }
  89071. }
  89072. });
  89073. };
  89074. /**
  89075. * Detaches the behavior from the mesh
  89076. */
  89077. MultiPointerScaleBehavior.prototype.detach = function () {
  89078. var _this = this;
  89079. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89080. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89081. behavior.onDragStartObservable.clear();
  89082. behavior.onDragObservable.clear();
  89083. _this._ownerNode.removeBehavior(behavior);
  89084. });
  89085. };
  89086. return MultiPointerScaleBehavior;
  89087. }());
  89088. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89089. })(BABYLON || (BABYLON = {}));
  89090. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89091. var BABYLON;
  89092. (function (BABYLON) {
  89093. /**
  89094. * 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
  89095. */
  89096. var SixDofDragBehavior = /** @class */ (function () {
  89097. function SixDofDragBehavior() {
  89098. this._sceneRenderObserver = null;
  89099. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89100. this._moving = false;
  89101. this._startingOrientation = new BABYLON.Quaternion();
  89102. /**
  89103. * 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)
  89104. */
  89105. this.zDragFactor = 3;
  89106. /**
  89107. * If the behavior is currently in a dragging state
  89108. */
  89109. this.dragging = false;
  89110. /**
  89111. * 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)
  89112. */
  89113. this.dragDeltaRatio = 0.2;
  89114. /**
  89115. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89116. */
  89117. this.currentDraggingPointerID = -1;
  89118. }
  89119. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89120. /**
  89121. * The name of the behavior
  89122. */
  89123. get: function () {
  89124. return "SixDofDrag";
  89125. },
  89126. enumerable: true,
  89127. configurable: true
  89128. });
  89129. /**
  89130. * Initializes the behavior
  89131. */
  89132. SixDofDragBehavior.prototype.init = function () { };
  89133. /**
  89134. * Attaches the scale behavior the passed in mesh
  89135. * @param ownerNode The mesh that will be scaled around once attached
  89136. */
  89137. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89138. var _this = this;
  89139. this._ownerNode = ownerNode;
  89140. this._scene = this._ownerNode.getScene();
  89141. if (!SixDofDragBehavior._virtualScene) {
  89142. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89143. this._scene.getEngine().scenes.pop();
  89144. }
  89145. var pickedMesh = null;
  89146. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89147. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89148. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89149. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89150. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89151. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89152. var pickPredicate = function (m) {
  89153. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89154. };
  89155. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89156. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89157. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89158. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89159. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89160. }
  89161. pickedMesh = _this._ownerNode;
  89162. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89163. // Set position and orientation of the controller
  89164. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89165. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89166. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89167. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89168. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89169. if (!pickedMesh.rotationQuaternion) {
  89170. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89171. }
  89172. var oldParent = pickedMesh.parent;
  89173. pickedMesh.setParent(null);
  89174. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89175. pickedMesh.setParent(oldParent);
  89176. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89177. // Update state
  89178. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89179. _this.dragging = true;
  89180. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89181. }
  89182. }
  89183. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89184. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89185. _this.dragging = false;
  89186. _this._moving = false;
  89187. _this.currentDraggingPointerID = -1;
  89188. pickedMesh = null;
  89189. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89190. }
  89191. }
  89192. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89193. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89194. var zDragFactor = _this.zDragFactor;
  89195. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89196. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89197. zDragFactor = 0;
  89198. }
  89199. // Calculate controller drag distance in controller space
  89200. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89201. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89202. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89203. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89204. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89205. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89206. if (_this._virtualDragMesh.position.z < 0) {
  89207. _this._virtualDragMesh.position.z = 0;
  89208. }
  89209. // Update the controller position
  89210. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89211. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89212. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89213. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89214. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89215. if (pickedMesh.parent) {
  89216. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89217. }
  89218. if (!_this._moving) {
  89219. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89220. }
  89221. _this._moving = true;
  89222. }
  89223. }
  89224. });
  89225. var tmpQuaternion = new BABYLON.Quaternion();
  89226. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89227. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89228. if (_this.dragging && _this._moving && pickedMesh) {
  89229. // Slowly move mesh to avoid jitter
  89230. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89231. // Get change in rotation
  89232. tmpQuaternion.copyFrom(_this._startingOrientation);
  89233. tmpQuaternion.x = -tmpQuaternion.x;
  89234. tmpQuaternion.y = -tmpQuaternion.y;
  89235. tmpQuaternion.z = -tmpQuaternion.z;
  89236. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89237. // Convert change in rotation to only y axis rotation
  89238. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89239. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89240. // Slowly move mesh to avoid jitter
  89241. var oldParent = pickedMesh.parent;
  89242. pickedMesh.setParent(null);
  89243. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89244. pickedMesh.setParent(oldParent);
  89245. }
  89246. });
  89247. };
  89248. /**
  89249. * Detaches the behavior from the mesh
  89250. */
  89251. SixDofDragBehavior.prototype.detach = function () {
  89252. if (this._scene) {
  89253. this._scene.onPointerObservable.remove(this._pointerObserver);
  89254. }
  89255. if (this._ownerNode) {
  89256. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89257. }
  89258. if (this._virtualOriginMesh) {
  89259. this._virtualOriginMesh.dispose();
  89260. }
  89261. if (this._virtualDragMesh) {
  89262. this._virtualDragMesh.dispose();
  89263. }
  89264. };
  89265. return SixDofDragBehavior;
  89266. }());
  89267. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89268. })(BABYLON || (BABYLON = {}));
  89269. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89270. var BABYLON;
  89271. (function (BABYLON) {
  89272. /**
  89273. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89274. */
  89275. var Gizmo = /** @class */ (function () {
  89276. /**
  89277. * Creates a gizmo
  89278. * @param gizmoLayer The utility layer the gizmo will be added to
  89279. */
  89280. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89281. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89282. var _this = this;
  89283. this.gizmoLayer = gizmoLayer;
  89284. this._scaleFactor = 3;
  89285. this._tmpMatrix = new BABYLON.Matrix();
  89286. /**
  89287. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89288. */
  89289. this.updateGizmoRotationToMatchAttachedMesh = true;
  89290. /**
  89291. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89292. */
  89293. this.updateGizmoPositionToMatchAttachedMesh = true;
  89294. /**
  89295. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89296. */
  89297. this._updateScale = true;
  89298. this._interactionsEnabled = true;
  89299. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89300. var tempVector = new BABYLON.Vector3();
  89301. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89302. if (_this.attachedMesh) {
  89303. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89304. if (!_this._rootMesh.rotationQuaternion) {
  89305. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89306. }
  89307. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89308. tempVector.copyFrom(_this.attachedMesh.scaling);
  89309. if (_this.attachedMesh.scaling.x < 0) {
  89310. _this.attachedMesh.scaling.x *= -1;
  89311. }
  89312. if (_this.attachedMesh.scaling.y < 0) {
  89313. _this.attachedMesh.scaling.y *= -1;
  89314. }
  89315. if (_this.attachedMesh.scaling.z < 0) {
  89316. _this.attachedMesh.scaling.z *= -1;
  89317. }
  89318. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89319. _this.attachedMesh.scaling.copyFrom(tempVector);
  89320. _this.attachedMesh.computeWorldMatrix();
  89321. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89322. }
  89323. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89324. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89325. }
  89326. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89327. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89328. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89329. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89330. }
  89331. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89332. var dist = tempVector.length() / _this._scaleFactor;
  89333. _this._rootMesh.scaling.set(dist, dist, dist);
  89334. }
  89335. }
  89336. });
  89337. this.attachedMesh = null;
  89338. }
  89339. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89340. /**
  89341. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89342. * * When set, interactions will be enabled
  89343. */
  89344. get: function () {
  89345. return this._attachedMesh;
  89346. },
  89347. set: function (value) {
  89348. this._attachedMesh = value;
  89349. this._rootMesh.setEnabled(value ? true : false);
  89350. this._attachedMeshChanged(value);
  89351. },
  89352. enumerable: true,
  89353. configurable: true
  89354. });
  89355. Gizmo.prototype._attachedMeshChanged = function (value) {
  89356. };
  89357. /**
  89358. * Disposes of the gizmo
  89359. */
  89360. Gizmo.prototype.dispose = function () {
  89361. this._rootMesh.dispose();
  89362. if (this._beforeRenderObserver) {
  89363. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89364. }
  89365. };
  89366. return Gizmo;
  89367. }());
  89368. BABYLON.Gizmo = Gizmo;
  89369. })(BABYLON || (BABYLON = {}));
  89370. //# sourceMappingURL=babylon.gizmo.js.map
  89371. var BABYLON;
  89372. (function (BABYLON) {
  89373. /**
  89374. * Single axis drag gizmo
  89375. */
  89376. var AxisDragGizmo = /** @class */ (function (_super) {
  89377. __extends(AxisDragGizmo, _super);
  89378. /**
  89379. * Creates an AxisDragGizmo
  89380. * @param gizmoLayer The utility layer the gizmo will be added to
  89381. * @param dragAxis The axis which the gizmo will be able to drag on
  89382. * @param color The color of the gizmo
  89383. */
  89384. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89385. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89386. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89387. var _this = _super.call(this, gizmoLayer) || this;
  89388. _this._pointerObserver = null;
  89389. /**
  89390. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89391. */
  89392. _this.snapDistance = 0;
  89393. /**
  89394. * Event that fires each time the gizmo snaps to a new location.
  89395. * * snapDistance is the the change in distance
  89396. */
  89397. _this.onSnapObservable = new BABYLON.Observable();
  89398. // Create Material
  89399. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89400. coloredMaterial.disableLighting = true;
  89401. coloredMaterial.emissiveColor = color;
  89402. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89403. hoverMaterial.disableLighting = true;
  89404. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89405. // Build mesh on root node
  89406. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89407. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89408. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89409. arrow.addChild(arrowMesh);
  89410. arrow.addChild(arrowTail);
  89411. // Position arrow pointing in its drag axis
  89412. arrowMesh.scaling.scaleInPlace(0.05);
  89413. arrowMesh.material = coloredMaterial;
  89414. arrowMesh.rotation.x = Math.PI / 2;
  89415. arrowMesh.position.z += 0.3;
  89416. arrowTail.rotation.x = Math.PI / 2;
  89417. arrowTail.material = coloredMaterial;
  89418. arrowTail.position.z += 0.15;
  89419. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89420. _this._rootMesh.addChild(arrow);
  89421. var currentSnapDragDistance = 0;
  89422. var tmpVector = new BABYLON.Vector3();
  89423. var tmpSnapEvent = { snapDistance: 0 };
  89424. // Add drag behavior to handle events when the gizmo is dragged
  89425. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89426. _this.dragBehavior.moveAttached = false;
  89427. _this._rootMesh.addBehavior(_this.dragBehavior);
  89428. _this.dragBehavior.onDragObservable.add(function (event) {
  89429. if (_this.attachedMesh) {
  89430. // Snapping logic
  89431. if (_this.snapDistance == 0) {
  89432. _this.attachedMesh.position.addInPlace(event.delta);
  89433. }
  89434. else {
  89435. currentSnapDragDistance += event.dragDistance;
  89436. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89437. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89438. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89439. event.delta.normalizeToRef(tmpVector);
  89440. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89441. _this.attachedMesh.position.addInPlace(tmpVector);
  89442. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89443. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89444. }
  89445. }
  89446. }
  89447. });
  89448. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89449. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89450. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89451. m.material = hoverMaterial;
  89452. });
  89453. }
  89454. else {
  89455. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89456. m.material = coloredMaterial;
  89457. });
  89458. }
  89459. });
  89460. return _this;
  89461. }
  89462. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89463. if (this.dragBehavior) {
  89464. this.dragBehavior.enabled = value ? true : false;
  89465. }
  89466. };
  89467. /**
  89468. * Disposes of the gizmo
  89469. */
  89470. AxisDragGizmo.prototype.dispose = function () {
  89471. this.onSnapObservable.clear();
  89472. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89473. this.dragBehavior.detach();
  89474. _super.prototype.dispose.call(this);
  89475. };
  89476. return AxisDragGizmo;
  89477. }(BABYLON.Gizmo));
  89478. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89479. })(BABYLON || (BABYLON = {}));
  89480. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89481. var BABYLON;
  89482. (function (BABYLON) {
  89483. /**
  89484. * Single axis scale gizmo
  89485. */
  89486. var AxisScaleGizmo = /** @class */ (function (_super) {
  89487. __extends(AxisScaleGizmo, _super);
  89488. /**
  89489. * Creates an AxisScaleGizmo
  89490. * @param gizmoLayer The utility layer the gizmo will be added to
  89491. * @param dragAxis The axis which the gizmo will be able to scale on
  89492. * @param color The color of the gizmo
  89493. */
  89494. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89495. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89496. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89497. var _this = _super.call(this, gizmoLayer) || this;
  89498. _this._pointerObserver = null;
  89499. /**
  89500. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89501. */
  89502. _this.snapDistance = 0;
  89503. /**
  89504. * Event that fires each time the gizmo snaps to a new location.
  89505. * * snapDistance is the the change in distance
  89506. */
  89507. _this.onSnapObservable = new BABYLON.Observable();
  89508. // Create Material
  89509. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89510. coloredMaterial.disableLighting = true;
  89511. coloredMaterial.emissiveColor = color;
  89512. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89513. hoverMaterial.disableLighting = true;
  89514. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89515. // Build mesh on root node
  89516. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89517. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89518. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89519. arrow.addChild(arrowMesh);
  89520. arrow.addChild(arrowTail);
  89521. // Position arrow pointing in its drag axis
  89522. arrowMesh.scaling.scaleInPlace(0.1);
  89523. arrowMesh.material = coloredMaterial;
  89524. arrowMesh.rotation.x = Math.PI / 2;
  89525. arrowMesh.position.z += 0.3;
  89526. arrowTail.rotation.x = Math.PI / 2;
  89527. arrowTail.material = coloredMaterial;
  89528. arrowTail.position.z += 0.15;
  89529. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89530. _this._rootMesh.addChild(arrow);
  89531. // Add drag behavior to handle events when the gizmo is dragged
  89532. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89533. _this.dragBehavior.moveAttached = false;
  89534. _this._rootMesh.addBehavior(_this.dragBehavior);
  89535. var currentSnapDragDistance = 0;
  89536. var tmpVector = new BABYLON.Vector3();
  89537. var tmpSnapEvent = { snapDistance: 0 };
  89538. _this.dragBehavior.onDragObservable.add(function (event) {
  89539. if (_this.attachedMesh) {
  89540. // Snapping logic
  89541. var snapped = false;
  89542. var dragSteps = 0;
  89543. if (_this.snapDistance == 0) {
  89544. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89545. }
  89546. else {
  89547. currentSnapDragDistance += event.dragDistance;
  89548. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89549. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89550. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89551. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89552. snapped = true;
  89553. }
  89554. else {
  89555. tmpVector.scaleInPlace(0);
  89556. }
  89557. }
  89558. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89559. if (snapped) {
  89560. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89561. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89562. }
  89563. }
  89564. });
  89565. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89566. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89567. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89568. m.material = hoverMaterial;
  89569. });
  89570. }
  89571. else {
  89572. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89573. m.material = coloredMaterial;
  89574. });
  89575. }
  89576. });
  89577. return _this;
  89578. }
  89579. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89580. if (this.dragBehavior) {
  89581. this.dragBehavior.enabled = value ? true : false;
  89582. }
  89583. };
  89584. /**
  89585. * Disposes of the gizmo
  89586. */
  89587. AxisScaleGizmo.prototype.dispose = function () {
  89588. this.onSnapObservable.clear();
  89589. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89590. this.dragBehavior.detach();
  89591. _super.prototype.dispose.call(this);
  89592. };
  89593. return AxisScaleGizmo;
  89594. }(BABYLON.Gizmo));
  89595. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89596. })(BABYLON || (BABYLON = {}));
  89597. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89598. var BABYLON;
  89599. (function (BABYLON) {
  89600. /**
  89601. * Single plane rotation gizmo
  89602. */
  89603. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89604. __extends(PlaneRotationGizmo, _super);
  89605. /**
  89606. * Creates a PlaneRotationGizmo
  89607. * @param gizmoLayer The utility layer the gizmo will be added to
  89608. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89609. * @param color The color of the gizmo
  89610. */
  89611. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89612. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89613. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89614. var _this = _super.call(this, gizmoLayer) || this;
  89615. _this._pointerObserver = null;
  89616. /**
  89617. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89618. */
  89619. _this.snapDistance = 0;
  89620. /**
  89621. * Event that fires each time the gizmo snaps to a new location.
  89622. * * snapDistance is the the change in distance
  89623. */
  89624. _this.onSnapObservable = new BABYLON.Observable();
  89625. // Create Material
  89626. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89627. coloredMaterial.disableLighting = true;
  89628. coloredMaterial.emissiveColor = color;
  89629. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89630. hoverMaterial.disableLighting = true;
  89631. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89632. // Build mesh on root node
  89633. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89634. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89635. // Position arrow pointing in its drag axis
  89636. rotationMesh.scaling.scaleInPlace(0.1);
  89637. rotationMesh.material = coloredMaterial;
  89638. rotationMesh.rotation.x = Math.PI / 2;
  89639. parentMesh.addChild(rotationMesh);
  89640. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89641. _this._rootMesh.addChild(parentMesh);
  89642. // Add drag behavior to handle events when the gizmo is dragged
  89643. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89644. _this.dragBehavior.moveAttached = false;
  89645. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89646. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89647. _this._rootMesh.addBehavior(_this.dragBehavior);
  89648. var lastDragPosition = new BABYLON.Vector3();
  89649. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89650. if (_this.attachedMesh) {
  89651. lastDragPosition.copyFrom(e.dragPlanePoint);
  89652. }
  89653. });
  89654. var rotationMatrix = new BABYLON.Matrix();
  89655. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89656. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89657. var tmpSnapEvent = { snapDistance: 0 };
  89658. var currentSnapDragDistance = 0;
  89659. _this.dragBehavior.onDragObservable.add(function (event) {
  89660. if (_this.attachedMesh) {
  89661. if (!_this.attachedMesh.rotationQuaternion) {
  89662. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89663. }
  89664. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89665. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89666. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89667. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89668. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89669. var angle = Math.atan2(cross.length(), dot);
  89670. planeNormalTowardsCamera.copyFrom(planeNormal);
  89671. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89672. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89673. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89674. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89675. }
  89676. // Flip up vector depending on which side the camera is on
  89677. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89678. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89679. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89680. planeNormalTowardsCamera.scaleInPlace(-1);
  89681. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89682. }
  89683. }
  89684. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89685. if (halfCircleSide)
  89686. angle = -angle;
  89687. // Snapping logic
  89688. var snapped = false;
  89689. if (_this.snapDistance != 0) {
  89690. currentSnapDragDistance += angle;
  89691. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89692. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89693. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89694. angle = _this.snapDistance * dragSteps;
  89695. snapped = true;
  89696. }
  89697. else {
  89698. angle = 0;
  89699. }
  89700. }
  89701. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89702. var quaternionCoefficient = Math.sin(angle / 2);
  89703. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89704. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89705. // Rotate selected mesh quaternion over fixed axis
  89706. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89707. }
  89708. else {
  89709. // Rotate selected mesh quaternion over rotated axis
  89710. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89711. }
  89712. lastDragPosition.copyFrom(event.dragPlanePoint);
  89713. if (snapped) {
  89714. tmpSnapEvent.snapDistance = angle;
  89715. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89716. }
  89717. }
  89718. });
  89719. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89720. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89721. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89722. m.material = hoverMaterial;
  89723. });
  89724. }
  89725. else {
  89726. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89727. m.material = coloredMaterial;
  89728. });
  89729. }
  89730. });
  89731. return _this;
  89732. }
  89733. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89734. if (this.dragBehavior) {
  89735. this.dragBehavior.enabled = value ? true : false;
  89736. }
  89737. };
  89738. /**
  89739. * Disposes of the gizmo
  89740. */
  89741. PlaneRotationGizmo.prototype.dispose = function () {
  89742. this.onSnapObservable.clear();
  89743. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89744. this.dragBehavior.detach();
  89745. _super.prototype.dispose.call(this);
  89746. };
  89747. return PlaneRotationGizmo;
  89748. }(BABYLON.Gizmo));
  89749. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89750. })(BABYLON || (BABYLON = {}));
  89751. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89752. var BABYLON;
  89753. (function (BABYLON) {
  89754. /**
  89755. * Gizmo that enables dragging a mesh along 3 axis
  89756. */
  89757. var PositionGizmo = /** @class */ (function (_super) {
  89758. __extends(PositionGizmo, _super);
  89759. /**
  89760. * Creates a PositionGizmo
  89761. * @param gizmoLayer The utility layer the gizmo will be added to
  89762. */
  89763. function PositionGizmo(gizmoLayer) {
  89764. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89765. var _this = _super.call(this, gizmoLayer) || this;
  89766. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89767. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89768. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89769. _this.attachedMesh = null;
  89770. return _this;
  89771. }
  89772. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89773. set: function (mesh) {
  89774. if (this.xGizmo) {
  89775. this.xGizmo.attachedMesh = mesh;
  89776. this.yGizmo.attachedMesh = mesh;
  89777. this.zGizmo.attachedMesh = mesh;
  89778. }
  89779. },
  89780. enumerable: true,
  89781. configurable: true
  89782. });
  89783. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89784. get: function () {
  89785. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89786. },
  89787. set: function (value) {
  89788. if (this.xGizmo) {
  89789. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89790. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89791. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89792. }
  89793. },
  89794. enumerable: true,
  89795. configurable: true
  89796. });
  89797. /**
  89798. * Disposes of the gizmo
  89799. */
  89800. PositionGizmo.prototype.dispose = function () {
  89801. this.xGizmo.dispose();
  89802. this.yGizmo.dispose();
  89803. this.zGizmo.dispose();
  89804. };
  89805. return PositionGizmo;
  89806. }(BABYLON.Gizmo));
  89807. BABYLON.PositionGizmo = PositionGizmo;
  89808. })(BABYLON || (BABYLON = {}));
  89809. //# sourceMappingURL=babylon.positionGizmo.js.map
  89810. var BABYLON;
  89811. (function (BABYLON) {
  89812. /**
  89813. * Gizmo that enables rotating a mesh along 3 axis
  89814. */
  89815. var RotationGizmo = /** @class */ (function (_super) {
  89816. __extends(RotationGizmo, _super);
  89817. /**
  89818. * Creates a RotationGizmo
  89819. * @param gizmoLayer The utility layer the gizmo will be added to
  89820. */
  89821. function RotationGizmo(gizmoLayer) {
  89822. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89823. var _this = _super.call(this, gizmoLayer) || this;
  89824. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89825. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89826. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89827. _this.attachedMesh = null;
  89828. return _this;
  89829. }
  89830. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89831. set: function (mesh) {
  89832. if (this.xGizmo) {
  89833. this.xGizmo.attachedMesh = mesh;
  89834. this.yGizmo.attachedMesh = mesh;
  89835. this.zGizmo.attachedMesh = mesh;
  89836. }
  89837. },
  89838. enumerable: true,
  89839. configurable: true
  89840. });
  89841. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89842. get: function () {
  89843. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89844. },
  89845. set: function (value) {
  89846. if (this.xGizmo) {
  89847. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89848. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89849. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89850. }
  89851. },
  89852. enumerable: true,
  89853. configurable: true
  89854. });
  89855. /**
  89856. * Disposes of the gizmo
  89857. */
  89858. RotationGizmo.prototype.dispose = function () {
  89859. this.xGizmo.dispose();
  89860. this.yGizmo.dispose();
  89861. this.zGizmo.dispose();
  89862. };
  89863. return RotationGizmo;
  89864. }(BABYLON.Gizmo));
  89865. BABYLON.RotationGizmo = RotationGizmo;
  89866. })(BABYLON || (BABYLON = {}));
  89867. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89868. var BABYLON;
  89869. (function (BABYLON) {
  89870. /**
  89871. * Gizmo that enables scaling a mesh along 3 axis
  89872. */
  89873. var ScaleGizmo = /** @class */ (function (_super) {
  89874. __extends(ScaleGizmo, _super);
  89875. /**
  89876. * Creates a ScaleGizmo
  89877. * @param gizmoLayer The utility layer the gizmo will be added to
  89878. */
  89879. function ScaleGizmo(gizmoLayer) {
  89880. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89881. var _this = _super.call(this, gizmoLayer) || this;
  89882. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89883. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89884. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89885. _this.attachedMesh = null;
  89886. return _this;
  89887. }
  89888. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89889. set: function (mesh) {
  89890. if (this.xGizmo) {
  89891. this.xGizmo.attachedMesh = mesh;
  89892. this.yGizmo.attachedMesh = mesh;
  89893. this.zGizmo.attachedMesh = mesh;
  89894. }
  89895. },
  89896. enumerable: true,
  89897. configurable: true
  89898. });
  89899. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89900. get: function () {
  89901. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89902. },
  89903. set: function (value) {
  89904. if (this.xGizmo) {
  89905. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89906. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89907. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89908. }
  89909. },
  89910. enumerable: true,
  89911. configurable: true
  89912. });
  89913. /**
  89914. * Disposes of the gizmo
  89915. */
  89916. ScaleGizmo.prototype.dispose = function () {
  89917. this.xGizmo.dispose();
  89918. this.yGizmo.dispose();
  89919. this.zGizmo.dispose();
  89920. };
  89921. return ScaleGizmo;
  89922. }(BABYLON.Gizmo));
  89923. BABYLON.ScaleGizmo = ScaleGizmo;
  89924. })(BABYLON || (BABYLON = {}));
  89925. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89926. var BABYLON;
  89927. (function (BABYLON) {
  89928. /**
  89929. * Bounding box gizmo
  89930. */
  89931. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89932. __extends(BoundingBoxGizmo, _super);
  89933. /**
  89934. * Creates an BoundingBoxGizmo
  89935. * @param gizmoLayer The utility layer the gizmo will be added to
  89936. * @param color The color of the gizmo
  89937. */
  89938. function BoundingBoxGizmo(color, gizmoLayer) {
  89939. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89940. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89941. var _this = _super.call(this, gizmoLayer) || this;
  89942. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89943. _this._renderObserver = null;
  89944. _this._pointerObserver = null;
  89945. _this._scaleDragSpeed = 0.2;
  89946. _this._tmpQuaternion = new BABYLON.Quaternion();
  89947. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89948. /**
  89949. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89950. */
  89951. _this.rotationSphereSize = 0.1;
  89952. /**
  89953. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89954. */
  89955. _this.scaleBoxSize = 0.1;
  89956. /**
  89957. * 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)
  89958. */
  89959. _this.fixedDragMeshScreenSize = false;
  89960. /**
  89961. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89962. */
  89963. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89964. /**
  89965. * Fired when a rotation sphere or scale box is dragged
  89966. */
  89967. _this.onDragStartObservable = new BABYLON.Observable();
  89968. /**
  89969. * Fired when a rotation sphere or scale box drag is started
  89970. */
  89971. _this.onDragObservable = new BABYLON.Observable();
  89972. /**
  89973. * Fired when a rotation sphere or scale box drag is needed
  89974. */
  89975. _this.onDragEndObservable = new BABYLON.Observable();
  89976. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89977. _this._updateScale = false;
  89978. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  89979. // Create Materials
  89980. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89981. coloredMaterial.disableLighting = true;
  89982. coloredMaterial.emissiveColor = color;
  89983. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89984. hoverColoredMaterial.disableLighting = true;
  89985. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89986. // Build bounding box out of lines
  89987. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89988. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89989. var lines = [];
  89990. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89991. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89992. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89993. 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));
  89994. 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));
  89995. 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));
  89996. 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));
  89997. 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));
  89998. 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));
  89999. 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));
  90000. 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));
  90001. 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));
  90002. lines.forEach(function (l) {
  90003. l.color = color;
  90004. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90005. l.isPickable = false;
  90006. _this._lineBoundingBox.addChild(l);
  90007. });
  90008. _this._rootMesh.addChild(_this._lineBoundingBox);
  90009. // Create rotation spheres
  90010. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90011. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90012. var _loop_1 = function (i_1) {
  90013. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90014. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90015. sphere.material = coloredMaterial;
  90016. // Drag behavior
  90017. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90018. _dragBehavior.moveAttached = false;
  90019. _dragBehavior.updateDragPlane = false;
  90020. sphere.addBehavior(_dragBehavior);
  90021. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90022. var totalTurnAmountOfDrag = 0;
  90023. _dragBehavior.onDragStartObservable.add(function (event) {
  90024. startingTurnDirection.copyFrom(sphere.forward);
  90025. totalTurnAmountOfDrag = 0;
  90026. });
  90027. _dragBehavior.onDragObservable.add(function (event) {
  90028. _this.onDragObservable.notifyObservers({});
  90029. if (_this.attachedMesh) {
  90030. var worldDragDirection = startingTurnDirection;
  90031. // Project the world right on to the drag plane
  90032. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90033. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90034. // project drag delta on to the resulting drag axis and rotate based on that
  90035. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90036. // Rotate based on axis
  90037. if (!_this.attachedMesh.rotationQuaternion) {
  90038. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90039. }
  90040. if (!_this._anchorMesh.rotationQuaternion) {
  90041. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90042. }
  90043. // Do not allow the object to turn more than a full circle
  90044. totalTurnAmountOfDrag += projectDist;
  90045. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90046. if (i_1 >= 8) {
  90047. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90048. }
  90049. else if (i_1 >= 4) {
  90050. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90051. }
  90052. else {
  90053. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90054. }
  90055. // Rotate around center of bounding box
  90056. _this._anchorMesh.addChild(_this.attachedMesh);
  90057. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90058. _this._anchorMesh.removeChild(_this.attachedMesh);
  90059. }
  90060. }
  90061. });
  90062. // Selection/deselection
  90063. _dragBehavior.onDragStartObservable.add(function () {
  90064. _this.onDragStartObservable.notifyObservers({});
  90065. _this._selectNode(sphere);
  90066. });
  90067. _dragBehavior.onDragEndObservable.add(function () {
  90068. _this.onDragEndObservable.notifyObservers({});
  90069. _this._selectNode(null);
  90070. });
  90071. this_1._rotateSpheresParent.addChild(sphere);
  90072. };
  90073. var this_1 = this, _dragBehavior;
  90074. for (var i_1 = 0; i_1 < 12; i_1++) {
  90075. _loop_1(i_1);
  90076. }
  90077. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90078. // Create scale cubes
  90079. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90080. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90081. for (var i = 0; i < 2; i++) {
  90082. for (var j = 0; j < 2; j++) {
  90083. var _loop_2 = function () {
  90084. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90085. box.material = coloredMaterial;
  90086. // Dragging logic
  90087. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90088. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90089. _dragBehavior.moveAttached = false;
  90090. box.addBehavior(_dragBehavior);
  90091. _dragBehavior.onDragObservable.add(function (event) {
  90092. _this.onDragObservable.notifyObservers({});
  90093. if (_this.attachedMesh) {
  90094. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90095. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90096. _this._updateBoundingBox();
  90097. // Scale from the position of the opposite corner
  90098. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90099. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90100. _this._anchorMesh.addChild(_this.attachedMesh);
  90101. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90102. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90103. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90104. }
  90105. _this._anchorMesh.removeChild(_this.attachedMesh);
  90106. }
  90107. });
  90108. // Selection/deselection
  90109. _dragBehavior.onDragStartObservable.add(function () {
  90110. _this.onDragStartObservable.notifyObservers({});
  90111. _this._selectNode(box);
  90112. });
  90113. _dragBehavior.onDragEndObservable.add(function () {
  90114. _this.onDragEndObservable.notifyObservers({});
  90115. _this._selectNode(null);
  90116. });
  90117. this_2._scaleBoxesParent.addChild(box);
  90118. };
  90119. var this_2 = this, _dragBehavior;
  90120. for (var k = 0; k < 2; k++) {
  90121. _loop_2();
  90122. }
  90123. }
  90124. }
  90125. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90126. // Hover color change
  90127. var pointerIds = new Array();
  90128. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90129. if (!pointerIds[pointerInfo.event.pointerId]) {
  90130. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90131. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90132. pointerIds[pointerInfo.event.pointerId] = mesh;
  90133. mesh.material = hoverColoredMaterial;
  90134. }
  90135. });
  90136. }
  90137. else {
  90138. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90139. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90140. delete pointerIds[pointerInfo.event.pointerId];
  90141. }
  90142. }
  90143. });
  90144. // Update bounding box positions
  90145. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90146. _this._updateBoundingBox();
  90147. });
  90148. _this._updateBoundingBox();
  90149. return _this;
  90150. }
  90151. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90152. if (value) {
  90153. // Reset anchor mesh to match attached mesh's scale
  90154. // This is needed to avoid invalid box/sphere position on first drag
  90155. this._anchorMesh.addChild(value);
  90156. this._anchorMesh.removeChild(value);
  90157. this._updateBoundingBox();
  90158. }
  90159. };
  90160. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90161. this._rotateSpheresParent.getChildMeshes()
  90162. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90163. m.isVisible = (!selectedMesh || m == selectedMesh);
  90164. });
  90165. };
  90166. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90167. var _this = this;
  90168. mesh.computeWorldMatrix(true);
  90169. mesh.getChildMeshes().forEach(function (m) {
  90170. _this._recurseComputeWorld(m);
  90171. });
  90172. };
  90173. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90174. if (this.attachedMesh) {
  90175. // Rotate based on axis
  90176. if (!this.attachedMesh.rotationQuaternion) {
  90177. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90178. }
  90179. if (!this._anchorMesh.rotationQuaternion) {
  90180. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90181. }
  90182. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90183. // Store original position and reset mesh to origin before computing the bounding box
  90184. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90185. this._tmpVector.copyFrom(this.attachedMesh.position);
  90186. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90187. this.attachedMesh.position.set(0, 0, 0);
  90188. // Update bounding dimensions/positions
  90189. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90190. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90191. // Update gizmo to match bounding box scaling and rotation
  90192. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90193. 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);
  90194. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90195. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90196. this._lineBoundingBox.computeWorldMatrix();
  90197. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90198. // restore position/rotation values
  90199. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90200. this.attachedMesh.position.copyFrom(this._tmpVector);
  90201. this._recurseComputeWorld(this.attachedMesh);
  90202. }
  90203. // Update rotation sphere locations
  90204. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90205. for (var i = 0; i < 3; i++) {
  90206. for (var j = 0; j < 2; j++) {
  90207. for (var k = 0; k < 2; k++) {
  90208. var index = ((i * 4) + (j * 2)) + k;
  90209. if (i == 0) {
  90210. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90211. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90212. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90213. }
  90214. if (i == 1) {
  90215. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90216. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90217. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90218. }
  90219. if (i == 2) {
  90220. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90221. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90222. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90223. }
  90224. if (this.fixedDragMeshScreenSize) {
  90225. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90226. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90227. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90228. }
  90229. else {
  90230. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90231. }
  90232. }
  90233. }
  90234. }
  90235. // Update scale box locations
  90236. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90237. for (var i = 0; i < 2; i++) {
  90238. for (var j = 0; j < 2; j++) {
  90239. for (var k = 0; k < 2; k++) {
  90240. var index = ((i * 4) + (j * 2)) + k;
  90241. if (scaleBoxes[index]) {
  90242. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90243. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90244. if (this.fixedDragMeshScreenSize) {
  90245. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90246. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90247. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90248. }
  90249. else {
  90250. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90251. }
  90252. }
  90253. }
  90254. }
  90255. }
  90256. };
  90257. /**
  90258. * Enables rotation on the specified axis and disables rotation on the others
  90259. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90260. */
  90261. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90262. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90263. if (i < 4) {
  90264. m.setEnabled(axis.indexOf("x") != -1);
  90265. }
  90266. else if (i < 8) {
  90267. m.setEnabled(axis.indexOf("y") != -1);
  90268. }
  90269. else {
  90270. m.setEnabled(axis.indexOf("z") != -1);
  90271. }
  90272. });
  90273. };
  90274. /**
  90275. * Disposes of the gizmo
  90276. */
  90277. BoundingBoxGizmo.prototype.dispose = function () {
  90278. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90279. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90280. this._lineBoundingBox.dispose();
  90281. this._rotateSpheresParent.dispose();
  90282. this._scaleBoxesParent.dispose();
  90283. _super.prototype.dispose.call(this);
  90284. };
  90285. /**
  90286. * 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)
  90287. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90288. * @returns the bounding box mesh with the passed in mesh as a child
  90289. */
  90290. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90291. var makeNotPickable = function (root) {
  90292. root.isPickable = false;
  90293. root.getChildMeshes().forEach(function (c) {
  90294. makeNotPickable(c);
  90295. });
  90296. };
  90297. makeNotPickable(mesh);
  90298. // Reset position to get boudning box from origin with no rotation
  90299. if (!mesh.rotationQuaternion) {
  90300. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  90301. }
  90302. var oldPos = mesh.position.clone();
  90303. var oldRot = mesh.rotationQuaternion.clone();
  90304. mesh.rotationQuaternion.set(0, 0, 0, 1);
  90305. mesh.position.set(0, 0, 0);
  90306. // Update bounding dimensions/positions
  90307. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  90308. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  90309. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  90310. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90311. // Restore original positions
  90312. mesh.addChild(box);
  90313. mesh.rotationQuaternion.copyFrom(oldRot);
  90314. mesh.position.copyFrom(oldPos);
  90315. // Reverse parenting
  90316. mesh.removeChild(box);
  90317. box.addChild(mesh);
  90318. box.visibility = 0;
  90319. return box;
  90320. };
  90321. return BoundingBoxGizmo;
  90322. }(BABYLON.Gizmo));
  90323. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90324. })(BABYLON || (BABYLON = {}));
  90325. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90326. var BABYLON;
  90327. (function (BABYLON) {
  90328. /**
  90329. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90330. */
  90331. var GizmoManager = /** @class */ (function () {
  90332. /**
  90333. * Instatiates a gizmo manager
  90334. * @param scene the scene to overlay the gizmos on top of
  90335. */
  90336. function GizmoManager(scene) {
  90337. var _this = this;
  90338. this.scene = scene;
  90339. this._pointerObserver = null;
  90340. this._attachedMesh = null;
  90341. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  90342. this._boundingBoxUtilLayer = null;
  90343. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  90344. /**
  90345. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  90346. */
  90347. this.attachableMeshes = null;
  90348. /**
  90349. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  90350. */
  90351. this.usePointerToAttachGizmos = true;
  90352. this._gizmoSet = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  90353. // Instatiate/dispose gizmos based on pointer actions
  90354. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90355. if (!_this.usePointerToAttachGizmos) {
  90356. return;
  90357. }
  90358. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90359. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90360. var node = pointerInfo.pickInfo.pickedMesh;
  90361. if (_this.attachableMeshes == null) {
  90362. // Attach to the most parent node
  90363. while (node && node.parent != null) {
  90364. node = node.parent;
  90365. }
  90366. }
  90367. else {
  90368. // Attach to the parent node that is an attachableMesh
  90369. var found = false;
  90370. _this.attachableMeshes.forEach(function (mesh) {
  90371. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  90372. node = mesh;
  90373. found = true;
  90374. }
  90375. });
  90376. if (!found) {
  90377. node = null;
  90378. }
  90379. }
  90380. if (node instanceof BABYLON.AbstractMesh) {
  90381. _this.attachToMesh(node);
  90382. }
  90383. }
  90384. else {
  90385. _this.attachToMesh(null);
  90386. }
  90387. }
  90388. });
  90389. }
  90390. /**
  90391. * Attaches a set of gizmos to the specified mesh
  90392. * @param mesh The mesh the gizmo's should be attached to
  90393. */
  90394. GizmoManager.prototype.attachToMesh = function (mesh) {
  90395. if (this._attachedMesh) {
  90396. this._attachedMesh.removeBehavior(this._dragBehavior);
  90397. }
  90398. this._attachedMesh = mesh;
  90399. for (var key in this._gizmoSet) {
  90400. var gizmo = (this._gizmoSet[key]);
  90401. if (gizmo) {
  90402. gizmo.attachedMesh = mesh;
  90403. }
  90404. }
  90405. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  90406. this._attachedMesh.addBehavior(this._dragBehavior);
  90407. }
  90408. };
  90409. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  90410. get: function () {
  90411. return this._gizmoSet.positionGizmo != null;
  90412. },
  90413. /**
  90414. * If the position gizmo is enabled
  90415. */
  90416. set: function (value) {
  90417. if (value) {
  90418. this._gizmoSet.positionGizmo = this._gizmoSet.positionGizmo || new BABYLON.PositionGizmo();
  90419. this._gizmoSet.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90420. this._gizmoSet.positionGizmo.attachedMesh = this._attachedMesh;
  90421. }
  90422. else if (this._gizmoSet.positionGizmo) {
  90423. this._gizmoSet.positionGizmo.dispose();
  90424. this._gizmoSet.positionGizmo = null;
  90425. }
  90426. },
  90427. enumerable: true,
  90428. configurable: true
  90429. });
  90430. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  90431. get: function () {
  90432. return this._gizmoSet.rotationGizmo != null;
  90433. },
  90434. /**
  90435. * If the rotation gizmo is enabled
  90436. */
  90437. set: function (value) {
  90438. if (value) {
  90439. this._gizmoSet.rotationGizmo = this._gizmoSet.rotationGizmo || new BABYLON.RotationGizmo();
  90440. this._gizmoSet.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90441. this._gizmoSet.rotationGizmo.attachedMesh = this._attachedMesh;
  90442. }
  90443. else if (this._gizmoSet.rotationGizmo) {
  90444. this._gizmoSet.rotationGizmo.dispose();
  90445. this._gizmoSet.rotationGizmo = null;
  90446. }
  90447. },
  90448. enumerable: true,
  90449. configurable: true
  90450. });
  90451. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  90452. get: function () {
  90453. return this._gizmoSet.scaleGizmo != null;
  90454. },
  90455. /**
  90456. * If the scale gizmo is enabled
  90457. */
  90458. set: function (value) {
  90459. if (value) {
  90460. this._gizmoSet.scaleGizmo = this._gizmoSet.scaleGizmo || new BABYLON.ScaleGizmo();
  90461. this._gizmoSet.scaleGizmo.attachedMesh = this._attachedMesh;
  90462. }
  90463. else if (this._gizmoSet.scaleGizmo) {
  90464. this._gizmoSet.scaleGizmo.dispose();
  90465. this._gizmoSet.scaleGizmo = null;
  90466. }
  90467. },
  90468. enumerable: true,
  90469. configurable: true
  90470. });
  90471. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  90472. get: function () {
  90473. return this._gizmoSet.boundingBoxGizmo != null;
  90474. },
  90475. /**
  90476. * If the boundingBox gizmo is enabled
  90477. */
  90478. set: function (value) {
  90479. if (value) {
  90480. if (!this._boundingBoxUtilLayer) {
  90481. this._boundingBoxUtilLayer = new BABYLON.UtilityLayerRenderer(this.scene);
  90482. this._boundingBoxUtilLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90483. }
  90484. this._gizmoSet.boundingBoxGizmo = this._gizmoSet.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._boundingBoxUtilLayer);
  90485. this._gizmoSet.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  90486. if (this._attachedMesh) {
  90487. this._attachedMesh.removeBehavior(this._dragBehavior);
  90488. this._attachedMesh.addBehavior(this._dragBehavior);
  90489. }
  90490. }
  90491. else if (this._gizmoSet.boundingBoxGizmo) {
  90492. this._gizmoSet.boundingBoxGizmo.dispose();
  90493. this._gizmoSet.boundingBoxGizmo = null;
  90494. }
  90495. },
  90496. enumerable: true,
  90497. configurable: true
  90498. });
  90499. /**
  90500. * Disposes of the gizmo manager
  90501. */
  90502. GizmoManager.prototype.dispose = function () {
  90503. this.scene.onPointerObservable.remove(this._pointerObserver);
  90504. for (var key in this._gizmoSet) {
  90505. var gizmo = (this._gizmoSet[key]);
  90506. if (gizmo) {
  90507. gizmo.dispose();
  90508. }
  90509. }
  90510. this._gizmoLayer.dispose();
  90511. };
  90512. return GizmoManager;
  90513. }());
  90514. BABYLON.GizmoManager = GizmoManager;
  90515. })(BABYLON || (BABYLON = {}));
  90516. //# sourceMappingURL=babylon.gizmoManager.js.map
  90517. var BABYLON;
  90518. (function (BABYLON) {
  90519. /**
  90520. * Defines a target to use with MorphTargetManager
  90521. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90522. */
  90523. var MorphTarget = /** @class */ (function () {
  90524. /**
  90525. * Creates a new MorphTarget
  90526. * @param name defines the name of the target
  90527. * @param influence defines the influence to use
  90528. */
  90529. function MorphTarget(
  90530. /** defines the name of the target */
  90531. name, influence, scene) {
  90532. if (influence === void 0) { influence = 0; }
  90533. if (scene === void 0) { scene = null; }
  90534. this.name = name;
  90535. /**
  90536. * Gets or sets the list of animations
  90537. */
  90538. this.animations = new Array();
  90539. this._positions = null;
  90540. this._normals = null;
  90541. this._tangents = null;
  90542. /**
  90543. * Observable raised when the influence changes
  90544. */
  90545. this.onInfluenceChanged = new BABYLON.Observable();
  90546. this._animationPropertiesOverride = null;
  90547. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90548. this.influence = influence;
  90549. }
  90550. Object.defineProperty(MorphTarget.prototype, "influence", {
  90551. /**
  90552. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90553. */
  90554. get: function () {
  90555. return this._influence;
  90556. },
  90557. set: function (influence) {
  90558. if (this._influence === influence) {
  90559. return;
  90560. }
  90561. var previous = this._influence;
  90562. this._influence = influence;
  90563. if (this.onInfluenceChanged.hasObservers) {
  90564. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90565. }
  90566. },
  90567. enumerable: true,
  90568. configurable: true
  90569. });
  90570. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90571. /**
  90572. * Gets or sets the animation properties override
  90573. */
  90574. get: function () {
  90575. if (!this._animationPropertiesOverride && this._scene) {
  90576. return this._scene.animationPropertiesOverride;
  90577. }
  90578. return this._animationPropertiesOverride;
  90579. },
  90580. set: function (value) {
  90581. this._animationPropertiesOverride = value;
  90582. },
  90583. enumerable: true,
  90584. configurable: true
  90585. });
  90586. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90587. /**
  90588. * Gets a boolean defining if the target contains position data
  90589. */
  90590. get: function () {
  90591. return !!this._positions;
  90592. },
  90593. enumerable: true,
  90594. configurable: true
  90595. });
  90596. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90597. /**
  90598. * Gets a boolean defining if the target contains normal data
  90599. */
  90600. get: function () {
  90601. return !!this._normals;
  90602. },
  90603. enumerable: true,
  90604. configurable: true
  90605. });
  90606. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90607. /**
  90608. * Gets a boolean defining if the target contains tangent data
  90609. */
  90610. get: function () {
  90611. return !!this._tangents;
  90612. },
  90613. enumerable: true,
  90614. configurable: true
  90615. });
  90616. /**
  90617. * Affects position data to this target
  90618. * @param data defines the position data to use
  90619. */
  90620. MorphTarget.prototype.setPositions = function (data) {
  90621. this._positions = data;
  90622. };
  90623. /**
  90624. * Gets the position data stored in this target
  90625. * @returns a FloatArray containing the position data (or null if not present)
  90626. */
  90627. MorphTarget.prototype.getPositions = function () {
  90628. return this._positions;
  90629. };
  90630. /**
  90631. * Affects normal data to this target
  90632. * @param data defines the normal data to use
  90633. */
  90634. MorphTarget.prototype.setNormals = function (data) {
  90635. this._normals = data;
  90636. };
  90637. /**
  90638. * Gets the normal data stored in this target
  90639. * @returns a FloatArray containing the normal data (or null if not present)
  90640. */
  90641. MorphTarget.prototype.getNormals = function () {
  90642. return this._normals;
  90643. };
  90644. /**
  90645. * Affects tangent data to this target
  90646. * @param data defines the tangent data to use
  90647. */
  90648. MorphTarget.prototype.setTangents = function (data) {
  90649. this._tangents = data;
  90650. };
  90651. /**
  90652. * Gets the tangent data stored in this target
  90653. * @returns a FloatArray containing the tangent data (or null if not present)
  90654. */
  90655. MorphTarget.prototype.getTangents = function () {
  90656. return this._tangents;
  90657. };
  90658. /**
  90659. * Serializes the current target into a Serialization object
  90660. * @returns the serialized object
  90661. */
  90662. MorphTarget.prototype.serialize = function () {
  90663. var serializationObject = {};
  90664. serializationObject.name = this.name;
  90665. serializationObject.influence = this.influence;
  90666. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90667. if (this.hasNormals) {
  90668. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90669. }
  90670. if (this.hasTangents) {
  90671. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90672. }
  90673. // Animations
  90674. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90675. return serializationObject;
  90676. };
  90677. // Statics
  90678. /**
  90679. * Creates a new target from serialized data
  90680. * @param serializationObject defines the serialized data to use
  90681. * @returns a new MorphTarget
  90682. */
  90683. MorphTarget.Parse = function (serializationObject) {
  90684. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90685. result.setPositions(serializationObject.positions);
  90686. if (serializationObject.normals) {
  90687. result.setNormals(serializationObject.normals);
  90688. }
  90689. if (serializationObject.tangents) {
  90690. result.setTangents(serializationObject.tangents);
  90691. }
  90692. // Animations
  90693. if (serializationObject.animations) {
  90694. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90695. var parsedAnimation = serializationObject.animations[animationIndex];
  90696. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90697. }
  90698. }
  90699. return result;
  90700. };
  90701. /**
  90702. * Creates a MorphTarget from mesh data
  90703. * @param mesh defines the source mesh
  90704. * @param name defines the name to use for the new target
  90705. * @param influence defines the influence to attach to the target
  90706. * @returns a new MorphTarget
  90707. */
  90708. MorphTarget.FromMesh = function (mesh, name, influence) {
  90709. if (!name) {
  90710. name = mesh.name;
  90711. }
  90712. var result = new MorphTarget(name, influence, mesh.getScene());
  90713. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90715. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90716. }
  90717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90718. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90719. }
  90720. return result;
  90721. };
  90722. return MorphTarget;
  90723. }());
  90724. BABYLON.MorphTarget = MorphTarget;
  90725. })(BABYLON || (BABYLON = {}));
  90726. //# sourceMappingURL=babylon.morphTarget.js.map
  90727. var BABYLON;
  90728. (function (BABYLON) {
  90729. /**
  90730. * This class is used to deform meshes using morphing between different targets
  90731. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90732. */
  90733. var MorphTargetManager = /** @class */ (function () {
  90734. /**
  90735. * Creates a new MorphTargetManager
  90736. * @param scene defines the current scene
  90737. */
  90738. function MorphTargetManager(scene) {
  90739. if (scene === void 0) { scene = null; }
  90740. this._targets = new Array();
  90741. this._targetObservable = new Array();
  90742. this._activeTargets = new BABYLON.SmartArray(16);
  90743. this._supportsNormals = false;
  90744. this._supportsTangents = false;
  90745. this._vertexCount = 0;
  90746. this._uniqueId = 0;
  90747. this._tempInfluences = new Array();
  90748. if (!scene) {
  90749. scene = BABYLON.Engine.LastCreatedScene;
  90750. }
  90751. this._scene = scene;
  90752. if (this._scene) {
  90753. this._scene.morphTargetManagers.push(this);
  90754. this._uniqueId = this._scene.getUniqueId();
  90755. }
  90756. }
  90757. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90758. /**
  90759. * Gets the unique ID of this manager
  90760. */
  90761. get: function () {
  90762. return this._uniqueId;
  90763. },
  90764. enumerable: true,
  90765. configurable: true
  90766. });
  90767. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90768. /**
  90769. * Gets the number of vertices handled by this manager
  90770. */
  90771. get: function () {
  90772. return this._vertexCount;
  90773. },
  90774. enumerable: true,
  90775. configurable: true
  90776. });
  90777. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90778. /**
  90779. * Gets a boolean indicating if this manager supports morphing of normals
  90780. */
  90781. get: function () {
  90782. return this._supportsNormals;
  90783. },
  90784. enumerable: true,
  90785. configurable: true
  90786. });
  90787. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90788. /**
  90789. * Gets a boolean indicating if this manager supports morphing of tangents
  90790. */
  90791. get: function () {
  90792. return this._supportsTangents;
  90793. },
  90794. enumerable: true,
  90795. configurable: true
  90796. });
  90797. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90798. /**
  90799. * Gets the number of targets stored in this manager
  90800. */
  90801. get: function () {
  90802. return this._targets.length;
  90803. },
  90804. enumerable: true,
  90805. configurable: true
  90806. });
  90807. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90808. /**
  90809. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90810. */
  90811. get: function () {
  90812. return this._activeTargets.length;
  90813. },
  90814. enumerable: true,
  90815. configurable: true
  90816. });
  90817. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90818. /**
  90819. * Gets the list of influences (one per target)
  90820. */
  90821. get: function () {
  90822. return this._influences;
  90823. },
  90824. enumerable: true,
  90825. configurable: true
  90826. });
  90827. /**
  90828. * Gets the active target at specified index. An active target is a target with an influence > 0
  90829. * @param index defines the index to check
  90830. * @returns the requested target
  90831. */
  90832. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90833. return this._activeTargets.data[index];
  90834. };
  90835. /**
  90836. * Gets the target at specified index
  90837. * @param index defines the index to check
  90838. * @returns the requested target
  90839. */
  90840. MorphTargetManager.prototype.getTarget = function (index) {
  90841. return this._targets[index];
  90842. };
  90843. /**
  90844. * Add a new target to this manager
  90845. * @param target defines the target to add
  90846. */
  90847. MorphTargetManager.prototype.addTarget = function (target) {
  90848. var _this = this;
  90849. this._targets.push(target);
  90850. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90851. _this._syncActiveTargets(needUpdate);
  90852. }));
  90853. this._syncActiveTargets(true);
  90854. };
  90855. /**
  90856. * Removes a target from the manager
  90857. * @param target defines the target to remove
  90858. */
  90859. MorphTargetManager.prototype.removeTarget = function (target) {
  90860. var index = this._targets.indexOf(target);
  90861. if (index >= 0) {
  90862. this._targets.splice(index, 1);
  90863. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90864. this._syncActiveTargets(true);
  90865. }
  90866. };
  90867. /**
  90868. * Serializes the current manager into a Serialization object
  90869. * @returns the serialized object
  90870. */
  90871. MorphTargetManager.prototype.serialize = function () {
  90872. var serializationObject = {};
  90873. serializationObject.id = this.uniqueId;
  90874. serializationObject.targets = [];
  90875. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90876. var target = _a[_i];
  90877. serializationObject.targets.push(target.serialize());
  90878. }
  90879. return serializationObject;
  90880. };
  90881. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90882. var influenceCount = 0;
  90883. this._activeTargets.reset();
  90884. this._supportsNormals = true;
  90885. this._supportsTangents = true;
  90886. this._vertexCount = 0;
  90887. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90888. var target = _a[_i];
  90889. this._activeTargets.push(target);
  90890. this._tempInfluences[influenceCount++] = target.influence;
  90891. var positions = target.getPositions();
  90892. if (positions) {
  90893. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90894. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90895. var vertexCount = positions.length / 3;
  90896. if (this._vertexCount === 0) {
  90897. this._vertexCount = vertexCount;
  90898. }
  90899. else if (this._vertexCount !== vertexCount) {
  90900. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90901. return;
  90902. }
  90903. }
  90904. }
  90905. if (!this._influences || this._influences.length !== influenceCount) {
  90906. this._influences = new Float32Array(influenceCount);
  90907. }
  90908. for (var index = 0; index < influenceCount; index++) {
  90909. this._influences[index] = this._tempInfluences[index];
  90910. }
  90911. if (needUpdate) {
  90912. this.synchronize();
  90913. }
  90914. };
  90915. /**
  90916. * Syncrhonize the targets with all the meshes using this morph target manager
  90917. */
  90918. MorphTargetManager.prototype.synchronize = function () {
  90919. if (!this._scene) {
  90920. return;
  90921. }
  90922. // Flag meshes as dirty to resync with the active targets
  90923. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90924. var mesh = _a[_i];
  90925. if (mesh.morphTargetManager === this) {
  90926. mesh._syncGeometryWithMorphTargetManager();
  90927. }
  90928. }
  90929. };
  90930. // Statics
  90931. /**
  90932. * Creates a new MorphTargetManager from serialized data
  90933. * @param serializationObject defines the serialized data
  90934. * @param scene defines the hosting scene
  90935. * @returns the new MorphTargetManager
  90936. */
  90937. MorphTargetManager.Parse = function (serializationObject, scene) {
  90938. var result = new MorphTargetManager(scene);
  90939. result._uniqueId = serializationObject.id;
  90940. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90941. var targetData = _a[_i];
  90942. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90943. }
  90944. return result;
  90945. };
  90946. return MorphTargetManager;
  90947. }());
  90948. BABYLON.MorphTargetManager = MorphTargetManager;
  90949. })(BABYLON || (BABYLON = {}));
  90950. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90951. var BABYLON;
  90952. (function (BABYLON) {
  90953. var Octree = /** @class */ (function () {
  90954. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90955. if (maxDepth === void 0) { maxDepth = 2; }
  90956. this.maxDepth = maxDepth;
  90957. this.dynamicContent = new Array();
  90958. this._maxBlockCapacity = maxBlockCapacity || 64;
  90959. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90960. this._creationFunc = creationFunc;
  90961. }
  90962. // Methods
  90963. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90964. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90965. };
  90966. Octree.prototype.addMesh = function (entry) {
  90967. for (var index = 0; index < this.blocks.length; index++) {
  90968. var block = this.blocks[index];
  90969. block.addEntry(entry);
  90970. }
  90971. };
  90972. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90973. this._selectionContent.reset();
  90974. for (var index = 0; index < this.blocks.length; index++) {
  90975. var block = this.blocks[index];
  90976. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90977. }
  90978. if (allowDuplicate) {
  90979. this._selectionContent.concat(this.dynamicContent);
  90980. }
  90981. else {
  90982. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90983. }
  90984. return this._selectionContent;
  90985. };
  90986. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90987. this._selectionContent.reset();
  90988. for (var index = 0; index < this.blocks.length; index++) {
  90989. var block = this.blocks[index];
  90990. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90991. }
  90992. if (allowDuplicate) {
  90993. this._selectionContent.concat(this.dynamicContent);
  90994. }
  90995. else {
  90996. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90997. }
  90998. return this._selectionContent;
  90999. };
  91000. Octree.prototype.intersectsRay = function (ray) {
  91001. this._selectionContent.reset();
  91002. for (var index = 0; index < this.blocks.length; index++) {
  91003. var block = this.blocks[index];
  91004. block.intersectsRay(ray, this._selectionContent);
  91005. }
  91006. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91007. return this._selectionContent;
  91008. };
  91009. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91010. target.blocks = new Array();
  91011. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91012. // Segmenting space
  91013. for (var x = 0; x < 2; x++) {
  91014. for (var y = 0; y < 2; y++) {
  91015. for (var z = 0; z < 2; z++) {
  91016. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91017. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91018. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91019. block.addEntries(entries);
  91020. target.blocks.push(block);
  91021. }
  91022. }
  91023. }
  91024. };
  91025. Octree.CreationFuncForMeshes = function (entry, block) {
  91026. var boundingInfo = entry.getBoundingInfo();
  91027. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91028. block.entries.push(entry);
  91029. }
  91030. };
  91031. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91032. var boundingInfo = entry.getBoundingInfo();
  91033. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91034. block.entries.push(entry);
  91035. }
  91036. };
  91037. return Octree;
  91038. }());
  91039. BABYLON.Octree = Octree;
  91040. })(BABYLON || (BABYLON = {}));
  91041. //# sourceMappingURL=babylon.octree.js.map
  91042. var BABYLON;
  91043. (function (BABYLON) {
  91044. var OctreeBlock = /** @class */ (function () {
  91045. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91046. this.entries = new Array();
  91047. this._boundingVectors = new Array();
  91048. this._capacity = capacity;
  91049. this._depth = depth;
  91050. this._maxDepth = maxDepth;
  91051. this._creationFunc = creationFunc;
  91052. this._minPoint = minPoint;
  91053. this._maxPoint = maxPoint;
  91054. this._boundingVectors.push(minPoint.clone());
  91055. this._boundingVectors.push(maxPoint.clone());
  91056. this._boundingVectors.push(minPoint.clone());
  91057. this._boundingVectors[2].x = maxPoint.x;
  91058. this._boundingVectors.push(minPoint.clone());
  91059. this._boundingVectors[3].y = maxPoint.y;
  91060. this._boundingVectors.push(minPoint.clone());
  91061. this._boundingVectors[4].z = maxPoint.z;
  91062. this._boundingVectors.push(maxPoint.clone());
  91063. this._boundingVectors[5].z = minPoint.z;
  91064. this._boundingVectors.push(maxPoint.clone());
  91065. this._boundingVectors[6].x = minPoint.x;
  91066. this._boundingVectors.push(maxPoint.clone());
  91067. this._boundingVectors[7].y = minPoint.y;
  91068. }
  91069. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91070. // Property
  91071. get: function () {
  91072. return this._capacity;
  91073. },
  91074. enumerable: true,
  91075. configurable: true
  91076. });
  91077. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91078. get: function () {
  91079. return this._minPoint;
  91080. },
  91081. enumerable: true,
  91082. configurable: true
  91083. });
  91084. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91085. get: function () {
  91086. return this._maxPoint;
  91087. },
  91088. enumerable: true,
  91089. configurable: true
  91090. });
  91091. // Methods
  91092. OctreeBlock.prototype.addEntry = function (entry) {
  91093. if (this.blocks) {
  91094. for (var index = 0; index < this.blocks.length; index++) {
  91095. var block = this.blocks[index];
  91096. block.addEntry(entry);
  91097. }
  91098. return;
  91099. }
  91100. this._creationFunc(entry, this);
  91101. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91102. this.createInnerBlocks();
  91103. }
  91104. };
  91105. OctreeBlock.prototype.addEntries = function (entries) {
  91106. for (var index = 0; index < entries.length; index++) {
  91107. var mesh = entries[index];
  91108. this.addEntry(mesh);
  91109. }
  91110. };
  91111. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91112. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91113. if (this.blocks) {
  91114. for (var index = 0; index < this.blocks.length; index++) {
  91115. var block = this.blocks[index];
  91116. block.select(frustumPlanes, selection, allowDuplicate);
  91117. }
  91118. return;
  91119. }
  91120. if (allowDuplicate) {
  91121. selection.concat(this.entries);
  91122. }
  91123. else {
  91124. selection.concatWithNoDuplicate(this.entries);
  91125. }
  91126. }
  91127. };
  91128. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91129. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91130. if (this.blocks) {
  91131. for (var index = 0; index < this.blocks.length; index++) {
  91132. var block = this.blocks[index];
  91133. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91134. }
  91135. return;
  91136. }
  91137. if (allowDuplicate) {
  91138. selection.concat(this.entries);
  91139. }
  91140. else {
  91141. selection.concatWithNoDuplicate(this.entries);
  91142. }
  91143. }
  91144. };
  91145. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91146. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91147. if (this.blocks) {
  91148. for (var index = 0; index < this.blocks.length; index++) {
  91149. var block = this.blocks[index];
  91150. block.intersectsRay(ray, selection);
  91151. }
  91152. return;
  91153. }
  91154. selection.concatWithNoDuplicate(this.entries);
  91155. }
  91156. };
  91157. OctreeBlock.prototype.createInnerBlocks = function () {
  91158. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91159. };
  91160. return OctreeBlock;
  91161. }());
  91162. BABYLON.OctreeBlock = OctreeBlock;
  91163. })(BABYLON || (BABYLON = {}));
  91164. //# sourceMappingURL=babylon.octreeBlock.js.map
  91165. var BABYLON;
  91166. (function (BABYLON) {
  91167. /**
  91168. * Postprocess used to generate anaglyphic rendering
  91169. */
  91170. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91171. __extends(AnaglyphPostProcess, _super);
  91172. /**
  91173. * Creates a new AnaglyphPostProcess
  91174. * @param name defines postprocess name
  91175. * @param options defines creation options or target ratio scale
  91176. * @param rigCameras defines cameras using this postprocess
  91177. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91178. * @param engine defines hosting engine
  91179. * @param reusable defines if the postprocess will be reused multiple times per frame
  91180. */
  91181. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91182. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91183. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91184. _this.onApplyObservable.add(function (effect) {
  91185. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91186. });
  91187. return _this;
  91188. }
  91189. return AnaglyphPostProcess;
  91190. }(BABYLON.PostProcess));
  91191. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91192. })(BABYLON || (BABYLON = {}));
  91193. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91194. var BABYLON;
  91195. (function (BABYLON) {
  91196. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91197. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91198. });
  91199. /**
  91200. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91201. */
  91202. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91203. __extends(AnaglyphArcRotateCamera, _super);
  91204. /**
  91205. * Creates a new AnaglyphArcRotateCamera
  91206. * @param name defines camera name
  91207. * @param alpha defines alpha angle (in radians)
  91208. * @param beta defines beta angle (in radians)
  91209. * @param radius defines radius
  91210. * @param target defines camera target
  91211. * @param interaxialDistance defines distance between each color axis
  91212. * @param scene defines the hosting scene
  91213. */
  91214. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91215. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91216. _this.interaxialDistance = interaxialDistance;
  91217. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91218. return _this;
  91219. }
  91220. /**
  91221. * Gets camera class name
  91222. * @returns AnaglyphArcRotateCamera
  91223. */
  91224. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91225. return "AnaglyphArcRotateCamera";
  91226. };
  91227. return AnaglyphArcRotateCamera;
  91228. }(BABYLON.ArcRotateCamera));
  91229. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91230. })(BABYLON || (BABYLON = {}));
  91231. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91232. var BABYLON;
  91233. (function (BABYLON) {
  91234. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91235. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91236. });
  91237. /**
  91238. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91239. */
  91240. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91241. __extends(AnaglyphFreeCamera, _super);
  91242. /**
  91243. * Creates a new AnaglyphFreeCamera
  91244. * @param name defines camera name
  91245. * @param position defines initial position
  91246. * @param interaxialDistance defines distance between each color axis
  91247. * @param scene defines the hosting scene
  91248. */
  91249. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91250. var _this = _super.call(this, name, position, scene) || this;
  91251. _this.interaxialDistance = interaxialDistance;
  91252. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91253. return _this;
  91254. }
  91255. /**
  91256. * Gets camera class name
  91257. * @returns AnaglyphFreeCamera
  91258. */
  91259. AnaglyphFreeCamera.prototype.getClassName = function () {
  91260. return "AnaglyphFreeCamera";
  91261. };
  91262. return AnaglyphFreeCamera;
  91263. }(BABYLON.FreeCamera));
  91264. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91265. })(BABYLON || (BABYLON = {}));
  91266. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91267. var BABYLON;
  91268. (function (BABYLON) {
  91269. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91270. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91271. });
  91272. /**
  91273. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91274. */
  91275. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91276. __extends(AnaglyphGamepadCamera, _super);
  91277. /**
  91278. * Creates a new AnaglyphGamepadCamera
  91279. * @param name defines camera name
  91280. * @param position defines initial position
  91281. * @param interaxialDistance defines distance between each color axis
  91282. * @param scene defines the hosting scene
  91283. */
  91284. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91285. var _this = _super.call(this, name, position, scene) || this;
  91286. _this.interaxialDistance = interaxialDistance;
  91287. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91288. return _this;
  91289. }
  91290. /**
  91291. * Gets camera class name
  91292. * @returns AnaglyphGamepadCamera
  91293. */
  91294. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91295. return "AnaglyphGamepadCamera";
  91296. };
  91297. return AnaglyphGamepadCamera;
  91298. }(BABYLON.GamepadCamera));
  91299. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91300. })(BABYLON || (BABYLON = {}));
  91301. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91302. var BABYLON;
  91303. (function (BABYLON) {
  91304. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91305. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91306. });
  91307. /**
  91308. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91309. */
  91310. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91311. __extends(AnaglyphUniversalCamera, _super);
  91312. /**
  91313. * Creates a new AnaglyphUniversalCamera
  91314. * @param name defines camera name
  91315. * @param position defines initial position
  91316. * @param interaxialDistance defines distance between each color axis
  91317. * @param scene defines the hosting scene
  91318. */
  91319. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91320. var _this = _super.call(this, name, position, scene) || this;
  91321. _this.interaxialDistance = interaxialDistance;
  91322. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91323. return _this;
  91324. }
  91325. /**
  91326. * Gets camera class name
  91327. * @returns AnaglyphUniversalCamera
  91328. */
  91329. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91330. return "AnaglyphUniversalCamera";
  91331. };
  91332. return AnaglyphUniversalCamera;
  91333. }(BABYLON.UniversalCamera));
  91334. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91335. })(BABYLON || (BABYLON = {}));
  91336. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91337. var BABYLON;
  91338. (function (BABYLON) {
  91339. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91340. __extends(StereoscopicInterlacePostProcess, _super);
  91341. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91342. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91343. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91344. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91345. _this.onSizeChangedObservable.add(function () {
  91346. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91347. });
  91348. _this.onApplyObservable.add(function (effect) {
  91349. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91350. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91351. });
  91352. return _this;
  91353. }
  91354. return StereoscopicInterlacePostProcess;
  91355. }(BABYLON.PostProcess));
  91356. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91357. })(BABYLON || (BABYLON = {}));
  91358. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91359. var BABYLON;
  91360. (function (BABYLON) {
  91361. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  91362. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91363. });
  91364. /**
  91365. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91366. */
  91367. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91368. __extends(StereoscopicArcRotateCamera, _super);
  91369. /**
  91370. * Creates a new StereoscopicArcRotateCamera
  91371. * @param name defines camera name
  91372. * @param alpha defines alpha angle (in radians)
  91373. * @param beta defines beta angle (in radians)
  91374. * @param radius defines radius
  91375. * @param target defines camera target
  91376. * @param interaxialDistance defines distance between each color axis
  91377. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91378. * @param scene defines the hosting scene
  91379. */
  91380. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91381. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91382. _this.interaxialDistance = interaxialDistance;
  91383. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91384. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91385. return _this;
  91386. }
  91387. /**
  91388. * Gets camera class name
  91389. * @returns StereoscopicArcRotateCamera
  91390. */
  91391. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91392. return "StereoscopicArcRotateCamera";
  91393. };
  91394. return StereoscopicArcRotateCamera;
  91395. }(BABYLON.ArcRotateCamera));
  91396. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91397. })(BABYLON || (BABYLON = {}));
  91398. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  91399. var BABYLON;
  91400. (function (BABYLON) {
  91401. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91402. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91403. });
  91404. /**
  91405. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91406. */
  91407. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91408. __extends(StereoscopicFreeCamera, _super);
  91409. /**
  91410. * Creates a new StereoscopicFreeCamera
  91411. * @param name defines camera name
  91412. * @param position defines initial position
  91413. * @param interaxialDistance defines distance between each color axis
  91414. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91415. * @param scene defines the hosting scene
  91416. */
  91417. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91418. var _this = _super.call(this, name, position, scene) || this;
  91419. _this.interaxialDistance = interaxialDistance;
  91420. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91421. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91422. return _this;
  91423. }
  91424. /**
  91425. * Gets camera class name
  91426. * @returns StereoscopicFreeCamera
  91427. */
  91428. StereoscopicFreeCamera.prototype.getClassName = function () {
  91429. return "StereoscopicFreeCamera";
  91430. };
  91431. return StereoscopicFreeCamera;
  91432. }(BABYLON.FreeCamera));
  91433. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91434. })(BABYLON || (BABYLON = {}));
  91435. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  91436. var BABYLON;
  91437. (function (BABYLON) {
  91438. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  91439. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91440. });
  91441. /**
  91442. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91443. */
  91444. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91445. __extends(StereoscopicGamepadCamera, _super);
  91446. /**
  91447. * Creates a new StereoscopicGamepadCamera
  91448. * @param name defines camera name
  91449. * @param position defines initial position
  91450. * @param interaxialDistance defines distance between each color axis
  91451. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91452. * @param scene defines the hosting scene
  91453. */
  91454. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91455. var _this = _super.call(this, name, position, scene) || this;
  91456. _this.interaxialDistance = interaxialDistance;
  91457. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91458. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91459. return _this;
  91460. }
  91461. /**
  91462. * Gets camera class name
  91463. * @returns StereoscopicGamepadCamera
  91464. */
  91465. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91466. return "StereoscopicGamepadCamera";
  91467. };
  91468. return StereoscopicGamepadCamera;
  91469. }(BABYLON.GamepadCamera));
  91470. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91471. })(BABYLON || (BABYLON = {}));
  91472. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  91473. var BABYLON;
  91474. (function (BABYLON) {
  91475. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91476. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91477. });
  91478. /**
  91479. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91480. */
  91481. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91482. __extends(StereoscopicUniversalCamera, _super);
  91483. /**
  91484. * Creates a new StereoscopicUniversalCamera
  91485. * @param name defines camera name
  91486. * @param position defines initial position
  91487. * @param interaxialDistance defines distance between each color axis
  91488. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91489. * @param scene defines the hosting scene
  91490. */
  91491. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91492. var _this = _super.call(this, name, position, scene) || this;
  91493. _this.interaxialDistance = interaxialDistance;
  91494. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91495. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91496. return _this;
  91497. }
  91498. /**
  91499. * Gets camera class name
  91500. * @returns StereoscopicUniversalCamera
  91501. */
  91502. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91503. return "StereoscopicUniversalCamera";
  91504. };
  91505. return StereoscopicUniversalCamera;
  91506. }(BABYLON.UniversalCamera));
  91507. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91508. })(BABYLON || (BABYLON = {}));
  91509. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  91510. var BABYLON;
  91511. (function (BABYLON) {
  91512. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91513. __extends(VRDistortionCorrectionPostProcess, _super);
  91514. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91515. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91516. 'LensCenter',
  91517. 'Scale',
  91518. 'ScaleIn',
  91519. 'HmdWarpParam'
  91520. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91521. _this._isRightEye = isRightEye;
  91522. _this._distortionFactors = vrMetrics.distortionK;
  91523. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91524. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91525. _this.adaptScaleToCurrentViewport = true;
  91526. _this.onSizeChangedObservable.add(function () {
  91527. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91528. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91529. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91530. });
  91531. _this.onApplyObservable.add(function (effect) {
  91532. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91533. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91534. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91535. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91536. });
  91537. return _this;
  91538. }
  91539. return VRDistortionCorrectionPostProcess;
  91540. }(BABYLON.PostProcess));
  91541. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91542. })(BABYLON || (BABYLON = {}));
  91543. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91544. var BABYLON;
  91545. (function (BABYLON) {
  91546. /**
  91547. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91548. * Screen rotation is taken into account.
  91549. */
  91550. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91551. function FreeCameraDeviceOrientationInput() {
  91552. var _this = this;
  91553. this._screenOrientationAngle = 0;
  91554. this._screenQuaternion = new BABYLON.Quaternion();
  91555. this._alpha = 0;
  91556. this._beta = 0;
  91557. this._gamma = 0;
  91558. this._orientationChanged = function () {
  91559. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91560. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91561. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91562. };
  91563. this._deviceOrientation = function (evt) {
  91564. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91565. _this._beta = evt.beta !== null ? evt.beta : 0;
  91566. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91567. };
  91568. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91569. this._orientationChanged();
  91570. }
  91571. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91572. get: function () {
  91573. return this._camera;
  91574. },
  91575. set: function (camera) {
  91576. this._camera = camera;
  91577. if (this._camera != null && !this._camera.rotationQuaternion) {
  91578. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91579. }
  91580. },
  91581. enumerable: true,
  91582. configurable: true
  91583. });
  91584. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91585. window.addEventListener("orientationchange", this._orientationChanged);
  91586. window.addEventListener("deviceorientation", this._deviceOrientation);
  91587. //In certain cases, the attach control is called AFTER orientation was changed,
  91588. //So this is needed.
  91589. this._orientationChanged();
  91590. };
  91591. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91592. window.removeEventListener("orientationchange", this._orientationChanged);
  91593. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91594. };
  91595. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91596. //if no device orientation provided, don't update the rotation.
  91597. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91598. if (!this._alpha)
  91599. return;
  91600. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91601. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91602. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91603. //Mirror on XY Plane
  91604. this._camera.rotationQuaternion.z *= -1;
  91605. this._camera.rotationQuaternion.w *= -1;
  91606. };
  91607. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91608. return "FreeCameraDeviceOrientationInput";
  91609. };
  91610. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91611. return "deviceOrientation";
  91612. };
  91613. return FreeCameraDeviceOrientationInput;
  91614. }());
  91615. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91616. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91617. })(BABYLON || (BABYLON = {}));
  91618. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91619. var BABYLON;
  91620. (function (BABYLON) {
  91621. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91622. function ArcRotateCameraVRDeviceOrientationInput() {
  91623. this.alphaCorrection = 1;
  91624. this.betaCorrection = 1;
  91625. this.gammaCorrection = 1;
  91626. this._alpha = 0;
  91627. this._gamma = 0;
  91628. this._dirty = false;
  91629. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91630. }
  91631. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91632. this.camera.attachControl(element, noPreventDefault);
  91633. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91634. };
  91635. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91636. if (evt.alpha !== null) {
  91637. this._alpha = +evt.alpha | 0;
  91638. }
  91639. if (evt.gamma !== null) {
  91640. this._gamma = +evt.gamma | 0;
  91641. }
  91642. this._dirty = true;
  91643. };
  91644. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91645. if (this._dirty) {
  91646. this._dirty = false;
  91647. if (this._gamma < 0) {
  91648. this._gamma = 180 + this._gamma;
  91649. }
  91650. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91651. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91652. }
  91653. };
  91654. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91655. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91656. };
  91657. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91658. return "ArcRotateCameraVRDeviceOrientationInput";
  91659. };
  91660. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91661. return "VRDeviceOrientation";
  91662. };
  91663. return ArcRotateCameraVRDeviceOrientationInput;
  91664. }());
  91665. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91666. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91667. })(BABYLON || (BABYLON = {}));
  91668. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91669. var BABYLON;
  91670. (function (BABYLON) {
  91671. var VRCameraMetrics = /** @class */ (function () {
  91672. function VRCameraMetrics() {
  91673. this.compensateDistortion = true;
  91674. }
  91675. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91676. get: function () {
  91677. return this.hResolution / (2 * this.vResolution);
  91678. },
  91679. enumerable: true,
  91680. configurable: true
  91681. });
  91682. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91683. get: function () {
  91684. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91685. },
  91686. enumerable: true,
  91687. configurable: true
  91688. });
  91689. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91690. get: function () {
  91691. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91692. var h = (4 * meters) / this.hScreenSize;
  91693. return BABYLON.Matrix.Translation(h, 0, 0);
  91694. },
  91695. enumerable: true,
  91696. configurable: true
  91697. });
  91698. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91699. get: function () {
  91700. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91701. var h = (4 * meters) / this.hScreenSize;
  91702. return BABYLON.Matrix.Translation(-h, 0, 0);
  91703. },
  91704. enumerable: true,
  91705. configurable: true
  91706. });
  91707. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91708. get: function () {
  91709. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91710. },
  91711. enumerable: true,
  91712. configurable: true
  91713. });
  91714. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91715. get: function () {
  91716. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91717. },
  91718. enumerable: true,
  91719. configurable: true
  91720. });
  91721. VRCameraMetrics.GetDefault = function () {
  91722. var result = new VRCameraMetrics();
  91723. result.hResolution = 1280;
  91724. result.vResolution = 800;
  91725. result.hScreenSize = 0.149759993;
  91726. result.vScreenSize = 0.0935999975;
  91727. result.vScreenCenter = 0.0467999987;
  91728. result.eyeToScreenDistance = 0.0410000011;
  91729. result.lensSeparationDistance = 0.0635000020;
  91730. result.interpupillaryDistance = 0.0640000030;
  91731. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91732. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91733. result.postProcessScaleFactor = 1.714605507808412;
  91734. result.lensCenterOffset = 0.151976421;
  91735. return result;
  91736. };
  91737. return VRCameraMetrics;
  91738. }());
  91739. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91740. })(BABYLON || (BABYLON = {}));
  91741. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91742. var BABYLON;
  91743. (function (BABYLON) {
  91744. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  91745. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91746. });
  91747. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  91748. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91749. });
  91750. /**
  91751. * This represents a WebVR camera.
  91752. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91753. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91754. */
  91755. var WebVRFreeCamera = /** @class */ (function (_super) {
  91756. __extends(WebVRFreeCamera, _super);
  91757. /**
  91758. * Instantiates a WebVRFreeCamera.
  91759. * @param name The name of the WebVRFreeCamera
  91760. * @param position The starting anchor position for the camera
  91761. * @param scene The scene the camera belongs to
  91762. * @param webVROptions a set of customizable options for the webVRCamera
  91763. */
  91764. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91765. if (webVROptions === void 0) { webVROptions = {}; }
  91766. var _this = _super.call(this, name, position, scene) || this;
  91767. _this.webVROptions = webVROptions;
  91768. /**
  91769. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91770. */
  91771. _this._vrDevice = null;
  91772. /**
  91773. * The rawPose of the vrDevice.
  91774. */
  91775. _this.rawPose = null;
  91776. _this._specsVersion = "1.1";
  91777. _this._attached = false;
  91778. _this._descendants = [];
  91779. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91780. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91781. /** @hidden */
  91782. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91783. _this._standingMatrix = null;
  91784. /**
  91785. * Represents device position in babylon space.
  91786. */
  91787. _this.devicePosition = BABYLON.Vector3.Zero();
  91788. /**
  91789. * Represents device rotation in babylon space.
  91790. */
  91791. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91792. /**
  91793. * The scale of the device to be used when translating from device space to babylon space.
  91794. */
  91795. _this.deviceScaleFactor = 1;
  91796. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91797. _this._worldToDevice = BABYLON.Matrix.Identity();
  91798. /**
  91799. * References to the webVR controllers for the vrDevice.
  91800. */
  91801. _this.controllers = [];
  91802. /**
  91803. * Emits an event when a controller is attached.
  91804. */
  91805. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91806. /**
  91807. * Emits an event when a controller's mesh has been loaded;
  91808. */
  91809. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91810. /**
  91811. * Emits an event when the HMD's pose has been updated.
  91812. */
  91813. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  91814. _this._poseSet = false;
  91815. /**
  91816. * If the rig cameras be used as parent instead of this camera.
  91817. */
  91818. _this.rigParenting = true;
  91819. _this._defaultHeight = undefined;
  91820. _this._workingVector = BABYLON.Vector3.Zero();
  91821. _this._oneVector = BABYLON.Vector3.One();
  91822. _this._workingMatrix = BABYLON.Matrix.Identity();
  91823. _this._cache.position = BABYLON.Vector3.Zero();
  91824. if (webVROptions.defaultHeight) {
  91825. _this._defaultHeight = webVROptions.defaultHeight;
  91826. _this.position.y = _this._defaultHeight;
  91827. }
  91828. _this.minZ = 0.1;
  91829. //legacy support - the compensation boolean was removed.
  91830. if (arguments.length === 5) {
  91831. _this.webVROptions = arguments[4];
  91832. }
  91833. // default webVR options
  91834. if (_this.webVROptions.trackPosition == undefined) {
  91835. _this.webVROptions.trackPosition = true;
  91836. }
  91837. if (_this.webVROptions.controllerMeshes == undefined) {
  91838. _this.webVROptions.controllerMeshes = true;
  91839. }
  91840. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91841. _this.webVROptions.defaultLightingOnControllers = true;
  91842. }
  91843. _this.rotationQuaternion = new BABYLON.Quaternion();
  91844. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91845. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91846. }
  91847. //enable VR
  91848. var engine = _this.getEngine();
  91849. _this._onVREnabled = function (success) { if (success) {
  91850. _this.initControllers();
  91851. } };
  91852. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91853. engine.initWebVR().add(function (event) {
  91854. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91855. return;
  91856. }
  91857. _this._vrDevice = event.vrDisplay;
  91858. //reset the rig parameters.
  91859. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91860. if (_this._attached) {
  91861. _this.getEngine().enableVR();
  91862. }
  91863. });
  91864. if (typeof (VRFrameData) !== "undefined")
  91865. _this._frameData = new VRFrameData();
  91866. /**
  91867. * The idea behind the following lines:
  91868. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91869. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91870. * the second will not show it correctly.
  91871. *
  91872. * To solve this - each object that has the camera as parent will be added to a protected array.
  91873. * When the rig camera renders, it will take this array and set all of those to be its children.
  91874. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91875. * Amazing!
  91876. */
  91877. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91878. if (camera.parent === _this && _this.rigParenting) {
  91879. _this._descendants = _this.getDescendants(true, function (n) {
  91880. // don't take the cameras or the controllers!
  91881. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91882. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91883. return !isController && !isRigCamera;
  91884. });
  91885. _this._descendants.forEach(function (node) {
  91886. node.parent = camera;
  91887. });
  91888. }
  91889. });
  91890. scene.onAfterCameraRenderObservable.add(function (camera) {
  91891. if (camera.parent === _this && _this.rigParenting) {
  91892. _this._descendants.forEach(function (node) {
  91893. node.parent = _this;
  91894. });
  91895. }
  91896. });
  91897. return _this;
  91898. }
  91899. /**
  91900. * Gets the device distance from the ground in meters.
  91901. * @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.
  91902. */
  91903. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91904. if (this._standingMatrix) {
  91905. // Add standing matrix offset to get real offset from ground in room
  91906. this._standingMatrix.getTranslationToRef(this._workingVector);
  91907. return this._deviceRoomPosition.y + this._workingVector.y;
  91908. }
  91909. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91910. return this._defaultHeight || 0;
  91911. };
  91912. /**
  91913. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91914. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91915. */
  91916. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91917. var _this = this;
  91918. if (callback === void 0) { callback = function (bool) { }; }
  91919. // Use standing matrix if available
  91920. this.getEngine().initWebVRAsync().then(function (result) {
  91921. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91922. callback(false);
  91923. }
  91924. else {
  91925. _this._standingMatrix = new BABYLON.Matrix();
  91926. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91927. if (!_this.getScene().useRightHandedSystem) {
  91928. [2, 6, 8, 9, 14].forEach(function (num) {
  91929. if (_this._standingMatrix) {
  91930. _this._standingMatrix.m[num] *= -1;
  91931. }
  91932. });
  91933. }
  91934. callback(true);
  91935. }
  91936. });
  91937. };
  91938. /**
  91939. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91940. * @returns A promise with a boolean set to if the standing matrix is supported.
  91941. */
  91942. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91943. var _this = this;
  91944. return new Promise(function (res, rej) {
  91945. _this.useStandingMatrix(function (supported) {
  91946. res(supported);
  91947. });
  91948. });
  91949. };
  91950. /**
  91951. * Disposes the camera
  91952. */
  91953. WebVRFreeCamera.prototype.dispose = function () {
  91954. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91955. _super.prototype.dispose.call(this);
  91956. };
  91957. /**
  91958. * Gets a vrController by name.
  91959. * @param name The name of the controller to retreive
  91960. * @returns the controller matching the name specified or null if not found
  91961. */
  91962. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91963. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91964. var gp = _a[_i];
  91965. if (gp.hand === name) {
  91966. return gp;
  91967. }
  91968. }
  91969. return null;
  91970. };
  91971. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91972. /**
  91973. * The controller corrisponding to the users left hand.
  91974. */
  91975. get: function () {
  91976. if (!this._leftController) {
  91977. this._leftController = this.getControllerByName("left");
  91978. }
  91979. return this._leftController;
  91980. },
  91981. enumerable: true,
  91982. configurable: true
  91983. });
  91984. ;
  91985. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91986. /**
  91987. * The controller corrisponding to the users right hand.
  91988. */
  91989. get: function () {
  91990. if (!this._rightController) {
  91991. this._rightController = this.getControllerByName("right");
  91992. }
  91993. return this._rightController;
  91994. },
  91995. enumerable: true,
  91996. configurable: true
  91997. });
  91998. ;
  91999. /**
  92000. * Casts a ray forward from the vrCamera's gaze.
  92001. * @param length Length of the ray (default: 100)
  92002. * @returns the ray corrisponding to the gaze
  92003. */
  92004. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92005. if (length === void 0) { length = 100; }
  92006. if (this.leftCamera) {
  92007. // Use left eye to avoid computation to compute center on every call
  92008. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92009. }
  92010. else {
  92011. return _super.prototype.getForwardRay.call(this, length);
  92012. }
  92013. };
  92014. /**
  92015. * Updates the camera based on device's frame data
  92016. */
  92017. WebVRFreeCamera.prototype._checkInputs = function () {
  92018. if (this._vrDevice && this._vrDevice.isPresenting) {
  92019. this._vrDevice.getFrameData(this._frameData);
  92020. this.updateFromDevice(this._frameData.pose);
  92021. }
  92022. _super.prototype._checkInputs.call(this);
  92023. };
  92024. /**
  92025. * Updates the poseControlled values based on the input device pose.
  92026. * @param poseData Pose coming from the device
  92027. */
  92028. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92029. if (poseData && poseData.orientation) {
  92030. this.rawPose = poseData;
  92031. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92032. if (this.getScene().useRightHandedSystem) {
  92033. this._deviceRoomRotationQuaternion.z *= -1;
  92034. this._deviceRoomRotationQuaternion.w *= -1;
  92035. }
  92036. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92037. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92038. if (this.getScene().useRightHandedSystem) {
  92039. this._deviceRoomPosition.z *= -1;
  92040. }
  92041. }
  92042. this._poseSet = true;
  92043. }
  92044. };
  92045. /**
  92046. * WebVR's attach control will start broadcasting frames to the device.
  92047. * Note that in certain browsers (chrome for example) this function must be called
  92048. * within a user-interaction callback. Example:
  92049. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92050. *
  92051. * @param element html element to attach the vrDevice to
  92052. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92053. */
  92054. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92055. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92056. this._attached = true;
  92057. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92058. if (this._vrDevice) {
  92059. this.getEngine().enableVR();
  92060. }
  92061. };
  92062. /**
  92063. * Detaches the camera from the html element and disables VR
  92064. *
  92065. * @param element html element to detach from
  92066. */
  92067. WebVRFreeCamera.prototype.detachControl = function (element) {
  92068. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92069. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92070. _super.prototype.detachControl.call(this, element);
  92071. this._attached = false;
  92072. this.getEngine().disableVR();
  92073. };
  92074. /**
  92075. * @returns the name of this class
  92076. */
  92077. WebVRFreeCamera.prototype.getClassName = function () {
  92078. return "WebVRFreeCamera";
  92079. };
  92080. /**
  92081. * Calls resetPose on the vrDisplay
  92082. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92083. */
  92084. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92085. //uses the vrDisplay's "resetPose()".
  92086. //pitch and roll won't be affected.
  92087. this._vrDevice.resetPose();
  92088. };
  92089. /**
  92090. * Updates the rig cameras (left and right eye)
  92091. */
  92092. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92093. var camLeft = this._rigCameras[0];
  92094. var camRight = this._rigCameras[1];
  92095. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92096. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92097. camLeft.position.copyFrom(this._deviceRoomPosition);
  92098. camRight.position.copyFrom(this._deviceRoomPosition);
  92099. };
  92100. /**
  92101. * Updates the cached values of the camera
  92102. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92103. */
  92104. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92105. var _this = this;
  92106. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92107. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92108. if (!this.updateCacheCalled) {
  92109. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92110. this.updateCacheCalled = true;
  92111. this.update();
  92112. }
  92113. // Set working vector to the device position in room space rotated by the new rotation
  92114. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92115. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92116. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92117. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92118. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92119. // Add translation from anchor position
  92120. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92121. this._workingVector.addInPlace(this.position);
  92122. this._workingVector.subtractInPlace(this._cache.position);
  92123. this._deviceToWorld.setTranslation(this._workingVector);
  92124. // Set an inverted matrix to be used when updating the camera
  92125. this._deviceToWorld.invertToRef(this._worldToDevice);
  92126. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92127. this.controllers.forEach(function (controller) {
  92128. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92129. controller.update();
  92130. });
  92131. }
  92132. if (!ignoreParentClass) {
  92133. _super.prototype._updateCache.call(this);
  92134. }
  92135. this.updateCacheCalled = false;
  92136. };
  92137. /**
  92138. * Updates the current device position and rotation in the babylon world
  92139. */
  92140. WebVRFreeCamera.prototype.update = function () {
  92141. // Get current device position in babylon world
  92142. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92143. // Get current device rotation in babylon world
  92144. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92145. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92146. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92147. if (this._poseSet) {
  92148. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92149. }
  92150. _super.prototype.update.call(this);
  92151. };
  92152. /**
  92153. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92154. * @returns an identity matrix
  92155. */
  92156. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92157. return BABYLON.Matrix.Identity();
  92158. };
  92159. /**
  92160. * This function is called by the two RIG cameras.
  92161. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92162. */
  92163. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92164. var _this = this;
  92165. // Update the parent camera prior to using a child camera to avoid desynchronization
  92166. var parentCamera = this._cameraRigParams["parentCamera"];
  92167. parentCamera._updateCache();
  92168. //WebVR 1.1
  92169. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92170. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92171. if (!this.getScene().useRightHandedSystem) {
  92172. [2, 6, 8, 9, 14].forEach(function (num) {
  92173. _this._webvrViewMatrix.m[num] *= -1;
  92174. });
  92175. }
  92176. // update the camera rotation matrix
  92177. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92178. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92179. // Computing target and final matrix
  92180. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92181. // should the view matrix be updated with scale and position offset?
  92182. if (parentCamera.deviceScaleFactor !== 1) {
  92183. this._webvrViewMatrix.invert();
  92184. // scale the position, if set
  92185. if (parentCamera.deviceScaleFactor) {
  92186. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92187. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92188. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92189. }
  92190. this._webvrViewMatrix.invert();
  92191. }
  92192. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92193. // Compute global position
  92194. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92195. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92196. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92197. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92198. this._markSyncedWithParent();
  92199. return this._webvrViewMatrix;
  92200. };
  92201. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92202. var _this = this;
  92203. var parentCamera = this.parent;
  92204. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92205. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92206. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92207. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92208. //babylon compatible matrix
  92209. if (!this.getScene().useRightHandedSystem) {
  92210. [8, 9, 10, 11].forEach(function (num) {
  92211. _this._projectionMatrix.m[num] *= -1;
  92212. });
  92213. }
  92214. return this._projectionMatrix;
  92215. };
  92216. /**
  92217. * Initializes the controllers and their meshes
  92218. */
  92219. WebVRFreeCamera.prototype.initControllers = function () {
  92220. var _this = this;
  92221. this.controllers = [];
  92222. var manager = this.getScene().gamepadManager;
  92223. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92224. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92225. var webVrController = gamepad;
  92226. if (webVrController.defaultModel) {
  92227. webVrController.defaultModel.setEnabled(false);
  92228. }
  92229. if (webVrController.hand === "right") {
  92230. _this._rightController = null;
  92231. }
  92232. if (webVrController.hand === "left") {
  92233. _this._leftController = null;
  92234. }
  92235. var controllerIndex = _this.controllers.indexOf(webVrController);
  92236. if (controllerIndex !== -1) {
  92237. _this.controllers.splice(controllerIndex, 1);
  92238. }
  92239. }
  92240. });
  92241. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92242. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92243. var webVrController_1 = gamepad;
  92244. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92245. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92246. if (_this.webVROptions.controllerMeshes) {
  92247. if (webVrController_1.defaultModel) {
  92248. webVrController_1.defaultModel.setEnabled(true);
  92249. }
  92250. else {
  92251. // Load the meshes
  92252. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92253. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92254. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92255. if (_this.webVROptions.defaultLightingOnControllers) {
  92256. if (!_this._lightOnControllers) {
  92257. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92258. }
  92259. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92260. var children = mesh.getChildren();
  92261. if (children.length !== 0) {
  92262. children.forEach(function (mesh) {
  92263. light.includedOnlyMeshes.push(mesh);
  92264. activateLightOnSubMeshes_1(mesh, light);
  92265. });
  92266. }
  92267. };
  92268. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92269. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92270. }
  92271. });
  92272. }
  92273. }
  92274. webVrController_1.attachToPoseControlledCamera(_this);
  92275. // since this is async - sanity check. Is the controller already stored?
  92276. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92277. //add to the controllers array
  92278. _this.controllers.push(webVrController_1);
  92279. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92280. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92281. // So we're overriding setting left & right manually to be sure
  92282. var firstViveWandDetected = false;
  92283. for (var i = 0; i < _this.controllers.length; i++) {
  92284. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92285. if (!firstViveWandDetected) {
  92286. firstViveWandDetected = true;
  92287. _this.controllers[i].hand = "left";
  92288. }
  92289. else {
  92290. _this.controllers[i].hand = "right";
  92291. }
  92292. }
  92293. }
  92294. //did we find enough controllers? Great! let the developer know.
  92295. if (_this.controllers.length >= 2) {
  92296. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92297. }
  92298. }
  92299. }
  92300. });
  92301. };
  92302. return WebVRFreeCamera;
  92303. }(BABYLON.FreeCamera));
  92304. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92305. })(BABYLON || (BABYLON = {}));
  92306. //# sourceMappingURL=babylon.webVRCamera.js.map
  92307. var BABYLON;
  92308. (function (BABYLON) {
  92309. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92310. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92311. });
  92312. // We're mainly based on the logic defined into the FreeCamera code
  92313. /**
  92314. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92315. * being tilted forward or back and left or right.
  92316. */
  92317. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92318. __extends(DeviceOrientationCamera, _super);
  92319. /**
  92320. * Creates a new device orientation camera
  92321. * @param name The name of the camera
  92322. * @param position The start position camera
  92323. * @param scene The scene the camera belongs to
  92324. */
  92325. function DeviceOrientationCamera(name, position, scene) {
  92326. var _this = _super.call(this, name, position, scene) || this;
  92327. _this._quaternionCache = new BABYLON.Quaternion();
  92328. _this.inputs.addDeviceOrientation();
  92329. return _this;
  92330. }
  92331. /**
  92332. * Gets the current instance class name ("DeviceOrientationCamera").
  92333. * This helps avoiding instanceof at run time.
  92334. * @returns the class name
  92335. */
  92336. DeviceOrientationCamera.prototype.getClassName = function () {
  92337. return "DeviceOrientationCamera";
  92338. };
  92339. /**
  92340. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92341. */
  92342. DeviceOrientationCamera.prototype._checkInputs = function () {
  92343. _super.prototype._checkInputs.call(this);
  92344. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92345. if (this._initialQuaternion) {
  92346. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92347. }
  92348. };
  92349. /**
  92350. * Reset the camera to its default orientation on the specified axis only.
  92351. * @param axis The axis to reset
  92352. */
  92353. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92354. var _this = this;
  92355. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92356. //can only work if this camera has a rotation quaternion already.
  92357. if (!this.rotationQuaternion)
  92358. return;
  92359. if (!this._initialQuaternion) {
  92360. this._initialQuaternion = new BABYLON.Quaternion();
  92361. }
  92362. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92363. ['x', 'y', 'z'].forEach(function (axisName) {
  92364. if (!axis[axisName]) {
  92365. _this._initialQuaternion[axisName] = 0;
  92366. }
  92367. else {
  92368. _this._initialQuaternion[axisName] *= -1;
  92369. }
  92370. });
  92371. this._initialQuaternion.normalize();
  92372. //force rotation update
  92373. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92374. };
  92375. return DeviceOrientationCamera;
  92376. }(BABYLON.FreeCamera));
  92377. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92378. })(BABYLON || (BABYLON = {}));
  92379. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92380. var BABYLON;
  92381. (function (BABYLON) {
  92382. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92383. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92384. });
  92385. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92386. __extends(VRDeviceOrientationFreeCamera, _super);
  92387. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92388. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92389. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92390. var _this = _super.call(this, name, position, scene) || this;
  92391. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92392. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92393. return _this;
  92394. }
  92395. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92396. return "VRDeviceOrientationFreeCamera";
  92397. };
  92398. return VRDeviceOrientationFreeCamera;
  92399. }(BABYLON.DeviceOrientationCamera));
  92400. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92401. })(BABYLON || (BABYLON = {}));
  92402. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92403. var BABYLON;
  92404. (function (BABYLON) {
  92405. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92406. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92407. });
  92408. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92409. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92410. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92411. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92412. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92413. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92414. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92415. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92416. _this.inputs.addVRDeviceOrientation();
  92417. return _this;
  92418. }
  92419. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92420. return "VRDeviceOrientationArcRotateCamera";
  92421. };
  92422. return VRDeviceOrientationArcRotateCamera;
  92423. }(BABYLON.ArcRotateCamera));
  92424. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92425. })(BABYLON || (BABYLON = {}));
  92426. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92427. var BABYLON;
  92428. (function (BABYLON) {
  92429. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92430. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92431. });
  92432. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92433. __extends(VRDeviceOrientationGamepadCamera, _super);
  92434. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92435. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92436. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92437. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92438. _this.inputs.addGamepad();
  92439. return _this;
  92440. }
  92441. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92442. return "VRDeviceOrientationGamepadCamera";
  92443. };
  92444. return VRDeviceOrientationGamepadCamera;
  92445. }(BABYLON.VRDeviceOrientationFreeCamera));
  92446. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92447. })(BABYLON || (BABYLON = {}));
  92448. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92449. var BABYLON;
  92450. (function (BABYLON) {
  92451. var VRExperienceHelperGazer = /** @class */ (function () {
  92452. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92453. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92454. this.scene = scene;
  92455. this._pointerDownOnMeshAsked = false;
  92456. this._isActionableMesh = false;
  92457. this._teleportationRequestInitiated = false;
  92458. this._teleportationBackRequestInitiated = false;
  92459. this._rotationRightAsked = false;
  92460. this._rotationLeftAsked = false;
  92461. this._dpadPressed = true;
  92462. this._activePointer = false;
  92463. this._id = VRExperienceHelperGazer._idCounter++;
  92464. // Gaze tracker
  92465. if (!gazeTrackerToClone) {
  92466. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92467. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92468. this._gazeTracker.isPickable = false;
  92469. this._gazeTracker.isVisible = false;
  92470. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92471. targetMat.specularColor = BABYLON.Color3.Black();
  92472. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92473. targetMat.backFaceCulling = false;
  92474. this._gazeTracker.material = targetMat;
  92475. }
  92476. else {
  92477. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92478. }
  92479. }
  92480. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92481. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92482. };
  92483. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92484. this._pointerDownOnMeshAsked = true;
  92485. if (this._currentHit) {
  92486. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92487. }
  92488. };
  92489. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92490. if (this._currentHit) {
  92491. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92492. }
  92493. this._pointerDownOnMeshAsked = false;
  92494. };
  92495. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92496. this._activePointer = true;
  92497. };
  92498. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92499. this._activePointer = false;
  92500. };
  92501. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92502. if (distance === void 0) { distance = 100; }
  92503. };
  92504. VRExperienceHelperGazer.prototype.dispose = function () {
  92505. this._interactionsEnabled = false;
  92506. this._teleportationEnabled = false;
  92507. if (this._gazeTracker) {
  92508. this._gazeTracker.dispose();
  92509. }
  92510. };
  92511. VRExperienceHelperGazer._idCounter = 0;
  92512. return VRExperienceHelperGazer;
  92513. }());
  92514. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92515. __extends(VRExperienceHelperControllerGazer, _super);
  92516. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92517. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92518. _this.webVRController = webVRController;
  92519. // Laser pointer
  92520. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92521. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92522. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92523. laserPointerMaterial.alpha = 0.6;
  92524. _this._laserPointer.material = laserPointerMaterial;
  92525. _this._laserPointer.rotation.x = Math.PI / 2;
  92526. _this._laserPointer.position.z = -0.5;
  92527. _this._laserPointer.isVisible = false;
  92528. _this._laserPointer.isPickable = false;
  92529. if (!webVRController.mesh) {
  92530. // Create an empty mesh that is used prior to loading the high quality model
  92531. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92532. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92533. preloadPointerPose.rotation.x = -0.7;
  92534. preloadMesh.addChild(preloadPointerPose);
  92535. webVRController.attachToMesh(preloadMesh);
  92536. }
  92537. _this._setLaserPointerParent(webVRController.mesh);
  92538. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92539. _this._setLaserPointerParent(mesh);
  92540. });
  92541. return _this;
  92542. }
  92543. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92544. return this.webVRController.getForwardRay(length);
  92545. };
  92546. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92547. _super.prototype._activatePointer.call(this);
  92548. this._laserPointer.isVisible = true;
  92549. };
  92550. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92551. _super.prototype._deactivatePointer.call(this);
  92552. this._laserPointer.isVisible = false;
  92553. };
  92554. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92555. this._laserPointer.material.emissiveColor = color;
  92556. };
  92557. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92558. var makeNotPick = function (root) {
  92559. root.name += " laserPointer";
  92560. root.isPickable = false;
  92561. root.getChildMeshes().forEach(function (c) {
  92562. makeNotPick(c);
  92563. });
  92564. };
  92565. makeNotPick(mesh);
  92566. var childMeshes = mesh.getChildMeshes();
  92567. this.webVRController._pointingPoseNode = null;
  92568. for (var i = 0; i < childMeshes.length; i++) {
  92569. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92570. mesh = childMeshes[i];
  92571. this.webVRController._pointingPoseNode = mesh;
  92572. break;
  92573. }
  92574. }
  92575. this._laserPointer.parent = mesh;
  92576. };
  92577. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92578. if (distance === void 0) { distance = 100; }
  92579. this._laserPointer.scaling.y = distance;
  92580. this._laserPointer.position.z = -distance / 2;
  92581. };
  92582. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92583. _super.prototype.dispose.call(this);
  92584. this._laserPointer.dispose();
  92585. if (this._meshAttachedObserver) {
  92586. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92587. }
  92588. };
  92589. return VRExperienceHelperControllerGazer;
  92590. }(VRExperienceHelperGazer));
  92591. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92592. __extends(VRExperienceHelperCameraGazer, _super);
  92593. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92594. var _this = _super.call(this, scene) || this;
  92595. _this.getCamera = getCamera;
  92596. return _this;
  92597. }
  92598. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92599. var camera = this.getCamera();
  92600. if (camera) {
  92601. return camera.getForwardRay(length);
  92602. }
  92603. else {
  92604. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92605. }
  92606. };
  92607. return VRExperienceHelperCameraGazer;
  92608. }(VRExperienceHelperGazer));
  92609. /**
  92610. * Helps to quickly add VR support to an existing scene.
  92611. * See http://doc.babylonjs.com/how_to/webvr_helper
  92612. */
  92613. var VRExperienceHelper = /** @class */ (function () {
  92614. /**
  92615. * Instantiates a VRExperienceHelper.
  92616. * Helps to quickly add VR support to an existing scene.
  92617. * @param scene The scene the VRExperienceHelper belongs to.
  92618. * @param webVROptions Options to modify the vr experience helper's behavior.
  92619. */
  92620. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92621. if (webVROptions === void 0) { webVROptions = {}; }
  92622. var _this = this;
  92623. this.webVROptions = webVROptions;
  92624. // Can the system support WebVR, even if a headset isn't plugged in?
  92625. this._webVRsupported = false;
  92626. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92627. this._webVRready = false;
  92628. // Are we waiting for the requestPresent callback to complete?
  92629. this._webVRrequesting = false;
  92630. // Are we presenting to the headset right now?
  92631. this._webVRpresenting = false;
  92632. // Are we presenting in the fullscreen fallback?
  92633. this._fullscreenVRpresenting = false;
  92634. /**
  92635. * Observable raised when entering VR.
  92636. */
  92637. this.onEnteringVRObservable = new BABYLON.Observable();
  92638. /**
  92639. * Observable raised when exiting VR.
  92640. */
  92641. this.onExitingVRObservable = new BABYLON.Observable();
  92642. /**
  92643. * Observable raised when controller mesh is loaded.
  92644. */
  92645. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92646. this._useCustomVRButton = false;
  92647. this._teleportationRequested = false;
  92648. this._teleportActive = false;
  92649. this._floorMeshesCollection = [];
  92650. this._rotationAllowed = true;
  92651. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92652. this._isDefaultTeleportationTarget = true;
  92653. this._teleportationFillColor = "#444444";
  92654. this._teleportationBorderColor = "#FFFFFF";
  92655. this._rotationAngle = 0;
  92656. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92657. this._padSensibilityUp = 0.65;
  92658. this._padSensibilityDown = 0.35;
  92659. this.leftController = null;
  92660. this.rightController = null;
  92661. /**
  92662. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92663. */
  92664. this.onNewMeshSelected = new BABYLON.Observable();
  92665. /**
  92666. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92667. */
  92668. this.onNewMeshPicked = new BABYLON.Observable();
  92669. /**
  92670. * Observable raised before camera teleportation
  92671. */
  92672. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92673. /**
  92674. * Observable raised after camera teleportation
  92675. */
  92676. this.onAfterCameraTeleport = new BABYLON.Observable();
  92677. /**
  92678. * Observable raised when current selected mesh gets unselected
  92679. */
  92680. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92681. /**
  92682. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92683. */
  92684. this.teleportationEnabled = true;
  92685. this._teleportationInitialized = false;
  92686. this._interactionsEnabled = false;
  92687. this._interactionsRequested = false;
  92688. this._displayGaze = true;
  92689. this._displayLaserPointer = true;
  92690. this._onResize = function () {
  92691. _this.moveButtonToBottomRight();
  92692. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92693. _this.exitVR();
  92694. }
  92695. };
  92696. this._onFullscreenChange = function () {
  92697. if (document.fullscreen !== undefined) {
  92698. _this._fullscreenVRpresenting = document.fullscreen;
  92699. }
  92700. else if (document.mozFullScreen !== undefined) {
  92701. _this._fullscreenVRpresenting = document.mozFullScreen;
  92702. }
  92703. else if (document.webkitIsFullScreen !== undefined) {
  92704. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92705. }
  92706. else if (document.msIsFullScreen !== undefined) {
  92707. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92708. }
  92709. else if (document.msFullscreenElement !== undefined) {
  92710. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92711. }
  92712. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92713. _this.exitVR();
  92714. if (!_this._useCustomVRButton) {
  92715. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92716. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92717. }
  92718. }
  92719. };
  92720. this.beforeRender = function () {
  92721. if (_this.leftController && _this.leftController._activePointer) {
  92722. _this._castRayAndSelectObject(_this.leftController);
  92723. }
  92724. if (_this.rightController && _this.rightController._activePointer) {
  92725. _this._castRayAndSelectObject(_this.rightController);
  92726. }
  92727. if (_this._noControllerIsActive) {
  92728. _this._castRayAndSelectObject(_this._cameraGazer);
  92729. }
  92730. else {
  92731. _this._cameraGazer._gazeTracker.isVisible = false;
  92732. }
  92733. };
  92734. this._onNewGamepadConnected = function (gamepad) {
  92735. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92736. if (gamepad.leftStick) {
  92737. gamepad.onleftstickchanged(function (stickValues) {
  92738. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92739. // Listening to classic/xbox gamepad only if no VR controller is active
  92740. if ((!_this.leftController && !_this.rightController) ||
  92741. ((_this.leftController && !_this.leftController._activePointer) &&
  92742. (_this.rightController && !_this.rightController._activePointer))) {
  92743. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92744. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92745. }
  92746. }
  92747. });
  92748. }
  92749. if (gamepad.rightStick) {
  92750. gamepad.onrightstickchanged(function (stickValues) {
  92751. if (_this._teleportationInitialized) {
  92752. _this._checkRotate(stickValues, _this._cameraGazer);
  92753. }
  92754. });
  92755. }
  92756. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92757. gamepad.onbuttondown(function (buttonPressed) {
  92758. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92759. _this._cameraGazer._selectionPointerDown();
  92760. }
  92761. });
  92762. gamepad.onbuttonup(function (buttonPressed) {
  92763. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92764. _this._cameraGazer._selectionPointerUp();
  92765. }
  92766. });
  92767. }
  92768. }
  92769. else {
  92770. var webVRController = gamepad;
  92771. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92772. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92773. _this.rightController = controller;
  92774. }
  92775. else {
  92776. _this.leftController = controller;
  92777. }
  92778. _this._tryEnableInteractionOnController(controller);
  92779. }
  92780. };
  92781. // 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
  92782. this._tryEnableInteractionOnController = function (controller) {
  92783. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92784. _this._enableInteractionOnController(controller);
  92785. }
  92786. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92787. _this._enableTeleportationOnController(controller);
  92788. }
  92789. };
  92790. this._onNewGamepadDisconnected = function (gamepad) {
  92791. if (gamepad instanceof BABYLON.WebVRController) {
  92792. if (gamepad.hand === "left" && _this.leftController != null) {
  92793. _this.leftController.dispose();
  92794. _this.leftController = null;
  92795. }
  92796. if (gamepad.hand === "right" && _this.rightController != null) {
  92797. _this.rightController.dispose();
  92798. _this.rightController = null;
  92799. }
  92800. }
  92801. };
  92802. this._workingVector = BABYLON.Vector3.Zero();
  92803. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92804. this._workingMatrix = BABYLON.Matrix.Identity();
  92805. this._scene = scene;
  92806. this._canvas = scene.getEngine().getRenderingCanvas();
  92807. // Parse options
  92808. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92809. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92810. }
  92811. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92812. webVROptions.createDeviceOrientationCamera = true;
  92813. }
  92814. if (webVROptions.laserToggle === undefined) {
  92815. webVROptions.laserToggle = true;
  92816. }
  92817. if (webVROptions.defaultHeight === undefined) {
  92818. webVROptions.defaultHeight = 1.7;
  92819. }
  92820. if (webVROptions.useCustomVRButton) {
  92821. this._useCustomVRButton = true;
  92822. if (webVROptions.customVRButton) {
  92823. this._btnVR = webVROptions.customVRButton;
  92824. }
  92825. }
  92826. if (webVROptions.rayLength) {
  92827. this._rayLength = webVROptions.rayLength;
  92828. }
  92829. this._defaultHeight = webVROptions.defaultHeight;
  92830. if (webVROptions.positionScale) {
  92831. this._rayLength *= webVROptions.positionScale;
  92832. this._defaultHeight *= webVROptions.positionScale;
  92833. }
  92834. // Set position
  92835. if (this._scene.activeCamera) {
  92836. this._position = this._scene.activeCamera.position.clone();
  92837. }
  92838. else {
  92839. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92840. }
  92841. // Set non-vr camera
  92842. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92843. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92844. // Copy data from existing camera
  92845. if (this._scene.activeCamera) {
  92846. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92847. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92848. // Set rotation from previous camera
  92849. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92850. var targetCamera = this._scene.activeCamera;
  92851. if (targetCamera.rotationQuaternion) {
  92852. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92853. }
  92854. else {
  92855. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92856. }
  92857. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92858. }
  92859. }
  92860. this._scene.activeCamera = this._deviceOrientationCamera;
  92861. if (this._canvas) {
  92862. this._scene.activeCamera.attachControl(this._canvas);
  92863. }
  92864. }
  92865. else {
  92866. this._existingCamera = this._scene.activeCamera;
  92867. }
  92868. // Create VR cameras
  92869. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92870. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92871. }
  92872. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92873. this._webVRCamera.useStandingMatrix();
  92874. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92875. // Create default button
  92876. if (!this._useCustomVRButton) {
  92877. this._btnVR = document.createElement("BUTTON");
  92878. this._btnVR.className = "babylonVRicon";
  92879. this._btnVR.id = "babylonVRiconbtn";
  92880. this._btnVR.title = "Click to switch to VR";
  92881. 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) }";
  92882. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92883. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92884. // css += ".babylonVRicon.vrdisplaysupported { }";
  92885. // css += ".babylonVRicon.vrdisplayready { }";
  92886. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92887. var style = document.createElement('style');
  92888. style.appendChild(document.createTextNode(css));
  92889. document.getElementsByTagName('head')[0].appendChild(style);
  92890. this.moveButtonToBottomRight();
  92891. }
  92892. // VR button click event
  92893. if (this._btnVR) {
  92894. this._btnVR.addEventListener("click", function () {
  92895. if (!_this.isInVRMode) {
  92896. _this.enterVR();
  92897. }
  92898. else {
  92899. _this.exitVR();
  92900. }
  92901. });
  92902. }
  92903. // Window events
  92904. window.addEventListener("resize", this._onResize);
  92905. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92906. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92907. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92908. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92909. document.onmsfullscreenchange = this._onFullscreenChange;
  92910. // Display vr button when headset is connected
  92911. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92912. this.displayVRButton();
  92913. }
  92914. else {
  92915. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92916. if (e.vrDisplay) {
  92917. _this.displayVRButton();
  92918. }
  92919. });
  92920. }
  92921. // Exiting VR mode using 'ESC' key on desktop
  92922. this._onKeyDown = function (event) {
  92923. if (event.keyCode === 27 && _this.isInVRMode) {
  92924. _this.exitVR();
  92925. }
  92926. };
  92927. document.addEventListener("keydown", this._onKeyDown);
  92928. // Exiting VR mode double tapping the touch screen
  92929. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92930. if (_this.isInVRMode) {
  92931. _this.exitVR();
  92932. if (_this._fullscreenVRpresenting) {
  92933. _this._scene.getEngine().switchFullscreen(true);
  92934. }
  92935. }
  92936. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92937. // Listen for WebVR display changes
  92938. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92939. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92940. this._onVRRequestPresentStart = function () {
  92941. _this._webVRrequesting = true;
  92942. _this.updateButtonVisibility();
  92943. };
  92944. this._onVRRequestPresentComplete = function (success) {
  92945. _this._webVRrequesting = false;
  92946. _this.updateButtonVisibility();
  92947. };
  92948. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92949. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92950. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92951. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92952. scene.onDisposeObservable.add(function () {
  92953. _this.dispose();
  92954. });
  92955. // Gamepad connection events
  92956. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92957. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92958. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92959. this.updateButtonVisibility();
  92960. //create easing functions
  92961. this._circleEase = new BABYLON.CircleEase();
  92962. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92963. if (this.webVROptions.floorMeshes) {
  92964. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92965. }
  92966. }
  92967. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92968. /** Return this.onEnteringVRObservable
  92969. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92970. */
  92971. get: function () {
  92972. return this.onEnteringVRObservable;
  92973. },
  92974. enumerable: true,
  92975. configurable: true
  92976. });
  92977. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92978. /** Return this.onExitingVRObservable
  92979. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92980. */
  92981. get: function () {
  92982. return this.onExitingVRObservable;
  92983. },
  92984. enumerable: true,
  92985. configurable: true
  92986. });
  92987. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92988. /** Return this.onControllerMeshLoadedObservable
  92989. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92990. */
  92991. get: function () {
  92992. return this.onControllerMeshLoadedObservable;
  92993. },
  92994. enumerable: true,
  92995. configurable: true
  92996. });
  92997. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92998. /**
  92999. * The mesh used to display where the user is going to teleport.
  93000. */
  93001. get: function () {
  93002. return this._teleportationTarget;
  93003. },
  93004. /**
  93005. * Sets the mesh to be used to display where the user is going to teleport.
  93006. */
  93007. set: function (value) {
  93008. if (value) {
  93009. value.name = "teleportationTarget";
  93010. this._isDefaultTeleportationTarget = false;
  93011. this._teleportationTarget = value;
  93012. }
  93013. },
  93014. enumerable: true,
  93015. configurable: true
  93016. });
  93017. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93018. /**
  93019. * The mesh used to display where the user is selecting,
  93020. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93021. * See http://doc.babylonjs.com/resources/baking_transformations
  93022. */
  93023. get: function () {
  93024. return this._cameraGazer._gazeTracker;
  93025. },
  93026. set: function (value) {
  93027. if (value) {
  93028. this._cameraGazer._gazeTracker = value;
  93029. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93030. this._cameraGazer._gazeTracker.isPickable = false;
  93031. this._cameraGazer._gazeTracker.isVisible = false;
  93032. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93033. if (this.leftController) {
  93034. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93035. }
  93036. if (this.rightController) {
  93037. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93038. }
  93039. }
  93040. },
  93041. enumerable: true,
  93042. configurable: true
  93043. });
  93044. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93045. /**
  93046. * If the ray of the gaze should be displayed.
  93047. */
  93048. get: function () {
  93049. return this._displayGaze;
  93050. },
  93051. /**
  93052. * Sets if the ray of the gaze should be displayed.
  93053. */
  93054. set: function (value) {
  93055. this._displayGaze = value;
  93056. if (!value) {
  93057. this._cameraGazer._gazeTracker.isVisible = false;
  93058. if (this.leftController) {
  93059. this.leftController._gazeTracker.isVisible = false;
  93060. }
  93061. if (this.rightController) {
  93062. this.rightController._gazeTracker.isVisible = false;
  93063. }
  93064. }
  93065. },
  93066. enumerable: true,
  93067. configurable: true
  93068. });
  93069. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93070. /**
  93071. * If the ray of the LaserPointer should be displayed.
  93072. */
  93073. get: function () {
  93074. return this._displayLaserPointer;
  93075. },
  93076. /**
  93077. * Sets if the ray of the LaserPointer should be displayed.
  93078. */
  93079. set: function (value) {
  93080. this._displayLaserPointer = value;
  93081. if (!value) {
  93082. if (this.rightController) {
  93083. this.rightController._deactivatePointer();
  93084. this.rightController._gazeTracker.isVisible = false;
  93085. }
  93086. if (this.leftController) {
  93087. this.leftController._deactivatePointer();
  93088. this.leftController._gazeTracker.isVisible = false;
  93089. }
  93090. }
  93091. else {
  93092. if (this.rightController) {
  93093. this.rightController._activatePointer();
  93094. }
  93095. if (this.leftController) {
  93096. this.leftController._activatePointer();
  93097. }
  93098. }
  93099. },
  93100. enumerable: true,
  93101. configurable: true
  93102. });
  93103. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93104. /**
  93105. * The deviceOrientationCamera used as the camera when not in VR.
  93106. */
  93107. get: function () {
  93108. return this._deviceOrientationCamera;
  93109. },
  93110. enumerable: true,
  93111. configurable: true
  93112. });
  93113. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93114. /**
  93115. * Based on the current WebVR support, returns the current VR camera used.
  93116. */
  93117. get: function () {
  93118. if (this._webVRready) {
  93119. return this._webVRCamera;
  93120. }
  93121. else {
  93122. return this._scene.activeCamera;
  93123. }
  93124. },
  93125. enumerable: true,
  93126. configurable: true
  93127. });
  93128. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93129. /**
  93130. * The webVRCamera which is used when in VR.
  93131. */
  93132. get: function () {
  93133. return this._webVRCamera;
  93134. },
  93135. enumerable: true,
  93136. configurable: true
  93137. });
  93138. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93139. /**
  93140. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93141. */
  93142. get: function () {
  93143. return this._vrDeviceOrientationCamera;
  93144. },
  93145. enumerable: true,
  93146. configurable: true
  93147. });
  93148. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93149. get: function () {
  93150. var result = this._cameraGazer._teleportationRequestInitiated
  93151. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93152. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93153. return result;
  93154. },
  93155. enumerable: true,
  93156. configurable: true
  93157. });
  93158. // Raised when one of the controller has loaded successfully its associated default mesh
  93159. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93160. if (this.leftController && this.leftController.webVRController == webVRController) {
  93161. if (webVRController.mesh) {
  93162. this.leftController._setLaserPointerParent(webVRController.mesh);
  93163. }
  93164. }
  93165. if (this.rightController && this.rightController.webVRController == webVRController) {
  93166. if (webVRController.mesh) {
  93167. this.rightController._setLaserPointerParent(webVRController.mesh);
  93168. }
  93169. }
  93170. try {
  93171. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93172. }
  93173. catch (err) {
  93174. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93175. }
  93176. };
  93177. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93178. /**
  93179. * Gets a value indicating if we are currently in VR mode.
  93180. */
  93181. get: function () {
  93182. return this._webVRpresenting || this._fullscreenVRpresenting;
  93183. },
  93184. enumerable: true,
  93185. configurable: true
  93186. });
  93187. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93188. var vrDisplay = this._scene.getEngine().getVRDevice();
  93189. if (vrDisplay) {
  93190. var wasPresenting = this._webVRpresenting;
  93191. // A VR display is connected
  93192. this._webVRpresenting = vrDisplay.isPresenting;
  93193. if (wasPresenting && !this._webVRpresenting)
  93194. this.exitVR();
  93195. }
  93196. else {
  93197. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93198. }
  93199. this.updateButtonVisibility();
  93200. };
  93201. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93202. this._webVRsupported = eventArgs.vrSupported;
  93203. this._webVRready = !!eventArgs.vrDisplay;
  93204. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93205. this.updateButtonVisibility();
  93206. };
  93207. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93208. if (this._canvas && !this._useCustomVRButton) {
  93209. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93210. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93211. }
  93212. };
  93213. VRExperienceHelper.prototype.displayVRButton = function () {
  93214. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93215. document.body.appendChild(this._btnVR);
  93216. this._btnVRDisplayed = true;
  93217. }
  93218. };
  93219. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93220. if (!this._btnVR || this._useCustomVRButton) {
  93221. return;
  93222. }
  93223. this._btnVR.className = "babylonVRicon";
  93224. if (this.isInVRMode) {
  93225. this._btnVR.className += " vrdisplaypresenting";
  93226. }
  93227. else {
  93228. if (this._webVRready)
  93229. this._btnVR.className += " vrdisplayready";
  93230. if (this._webVRsupported)
  93231. this._btnVR.className += " vrdisplaysupported";
  93232. if (this._webVRrequesting)
  93233. this._btnVR.className += " vrdisplayrequesting";
  93234. }
  93235. };
  93236. /**
  93237. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93238. * Otherwise, will use the fullscreen API.
  93239. */
  93240. VRExperienceHelper.prototype.enterVR = function () {
  93241. if (this.onEnteringVRObservable) {
  93242. try {
  93243. this.onEnteringVRObservable.notifyObservers(this);
  93244. }
  93245. catch (err) {
  93246. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93247. }
  93248. }
  93249. if (this._scene.activeCamera) {
  93250. this._position = this._scene.activeCamera.position.clone();
  93251. // make sure that we return to the last active camera
  93252. this._existingCamera = this._scene.activeCamera;
  93253. }
  93254. if (this._webVRrequesting)
  93255. return;
  93256. // If WebVR is supported and a headset is connected
  93257. if (this._webVRready) {
  93258. if (!this._webVRpresenting) {
  93259. this._webVRCamera.position = this._position;
  93260. this._scene.activeCamera = this._webVRCamera;
  93261. }
  93262. }
  93263. else if (this._vrDeviceOrientationCamera) {
  93264. this._vrDeviceOrientationCamera.position = this._position;
  93265. if (this._scene.activeCamera) {
  93266. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93267. }
  93268. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93269. this._scene.getEngine().switchFullscreen(true);
  93270. this.updateButtonVisibility();
  93271. }
  93272. if (this._scene.activeCamera && this._canvas) {
  93273. this._scene.activeCamera.attachControl(this._canvas);
  93274. }
  93275. if (this._interactionsEnabled) {
  93276. this._scene.registerBeforeRender(this.beforeRender);
  93277. }
  93278. };
  93279. /**
  93280. * Attempt to exit VR, or fullscreen.
  93281. */
  93282. VRExperienceHelper.prototype.exitVR = function () {
  93283. if (this.onExitingVRObservable) {
  93284. try {
  93285. this.onExitingVRObservable.notifyObservers(this);
  93286. }
  93287. catch (err) {
  93288. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93289. }
  93290. }
  93291. if (this._webVRpresenting) {
  93292. this._scene.getEngine().disableVR();
  93293. }
  93294. if (this._scene.activeCamera) {
  93295. this._position = this._scene.activeCamera.position.clone();
  93296. }
  93297. if (this._deviceOrientationCamera) {
  93298. this._deviceOrientationCamera.position = this._position;
  93299. this._scene.activeCamera = this._deviceOrientationCamera;
  93300. if (this._canvas) {
  93301. this._scene.activeCamera.attachControl(this._canvas);
  93302. }
  93303. }
  93304. else if (this._existingCamera) {
  93305. this._existingCamera.position = this._position;
  93306. this._scene.activeCamera = this._existingCamera;
  93307. }
  93308. this.updateButtonVisibility();
  93309. if (this._interactionsEnabled) {
  93310. this._scene.unregisterBeforeRender(this.beforeRender);
  93311. }
  93312. // resize to update width and height when exiting vr exits fullscreen
  93313. this._scene.getEngine().resize();
  93314. };
  93315. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93316. /**
  93317. * The position of the vr experience helper.
  93318. */
  93319. get: function () {
  93320. return this._position;
  93321. },
  93322. /**
  93323. * Sets the position of the vr experience helper.
  93324. */
  93325. set: function (value) {
  93326. this._position = value;
  93327. if (this._scene.activeCamera) {
  93328. this._scene.activeCamera.position = value;
  93329. }
  93330. },
  93331. enumerable: true,
  93332. configurable: true
  93333. });
  93334. /**
  93335. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93336. */
  93337. VRExperienceHelper.prototype.enableInteractions = function () {
  93338. var _this = this;
  93339. if (!this._interactionsEnabled) {
  93340. this._interactionsRequested = true;
  93341. if (this.leftController) {
  93342. this._enableInteractionOnController(this.leftController);
  93343. }
  93344. if (this.rightController) {
  93345. this._enableInteractionOnController(this.rightController);
  93346. }
  93347. this.raySelectionPredicate = function (mesh) {
  93348. return mesh.isVisible && mesh.isPickable;
  93349. };
  93350. this.meshSelectionPredicate = function (mesh) {
  93351. return true;
  93352. };
  93353. this._raySelectionPredicate = function (mesh) {
  93354. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93355. && mesh.name.indexOf("teleportationTarget") === -1
  93356. && mesh.name.indexOf("torusTeleportation") === -1
  93357. && mesh.name.indexOf("laserPointer") === -1)) {
  93358. return _this.raySelectionPredicate(mesh);
  93359. }
  93360. return false;
  93361. };
  93362. this._interactionsEnabled = true;
  93363. }
  93364. };
  93365. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93366. get: function () {
  93367. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93368. },
  93369. enumerable: true,
  93370. configurable: true
  93371. });
  93372. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93373. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93374. if (this._floorMeshesCollection[i].id === mesh.id) {
  93375. return true;
  93376. }
  93377. }
  93378. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93379. return true;
  93380. }
  93381. return false;
  93382. };
  93383. /**
  93384. * Adds a floor mesh to be used for teleportation.
  93385. * @param floorMesh the mesh to be used for teleportation.
  93386. */
  93387. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93388. if (!this._floorMeshesCollection) {
  93389. return;
  93390. }
  93391. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93392. return;
  93393. }
  93394. this._floorMeshesCollection.push(floorMesh);
  93395. };
  93396. /**
  93397. * Removes a floor mesh from being used for teleportation.
  93398. * @param floorMesh the mesh to be removed.
  93399. */
  93400. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93401. if (!this._floorMeshesCollection) {
  93402. return;
  93403. }
  93404. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93405. if (meshIndex !== -1) {
  93406. this._floorMeshesCollection.splice(meshIndex, 1);
  93407. }
  93408. };
  93409. /**
  93410. * Enables interactions and teleportation using the VR controllers and gaze.
  93411. * @param vrTeleportationOptions options to modify teleportation behavior.
  93412. */
  93413. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93414. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93415. if (!this._teleportationInitialized) {
  93416. this._teleportationRequested = true;
  93417. this.enableInteractions();
  93418. if (vrTeleportationOptions.floorMeshName) {
  93419. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93420. }
  93421. if (vrTeleportationOptions.floorMeshes) {
  93422. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93423. }
  93424. if (this.leftController != null) {
  93425. this._enableTeleportationOnController(this.leftController);
  93426. }
  93427. if (this.rightController != null) {
  93428. this._enableTeleportationOnController(this.rightController);
  93429. }
  93430. // Creates an image processing post process for the vignette not relying
  93431. // on the main scene configuration for image processing to reduce setup and spaces
  93432. // (gamma/linear) conflicts.
  93433. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93434. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93435. imageProcessingConfiguration.vignetteEnabled = true;
  93436. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93437. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93438. this._teleportationInitialized = true;
  93439. if (this._isDefaultTeleportationTarget) {
  93440. this._createTeleportationCircles();
  93441. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93442. }
  93443. }
  93444. };
  93445. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93446. var _this = this;
  93447. var controllerMesh = controller.webVRController.mesh;
  93448. if (controllerMesh) {
  93449. controller._interactionsEnabled = true;
  93450. controller._activatePointer();
  93451. if (this.webVROptions.laserToggle) {
  93452. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93453. // Enabling / disabling laserPointer
  93454. if (_this._displayLaserPointer && stateObject.value === 1) {
  93455. if (controller._activePointer) {
  93456. controller._deactivatePointer();
  93457. }
  93458. else {
  93459. controller._activatePointer();
  93460. }
  93461. if (_this.displayGaze) {
  93462. controller._gazeTracker.isVisible = controller._activePointer;
  93463. }
  93464. }
  93465. });
  93466. }
  93467. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93468. var gazer = controller;
  93469. if (_this._noControllerIsActive) {
  93470. gazer = _this._cameraGazer;
  93471. }
  93472. if (!gazer._pointerDownOnMeshAsked) {
  93473. if (stateObject.value > _this._padSensibilityUp) {
  93474. gazer._selectionPointerDown();
  93475. }
  93476. }
  93477. else if (stateObject.value < _this._padSensibilityDown) {
  93478. gazer._selectionPointerUp();
  93479. }
  93480. });
  93481. }
  93482. };
  93483. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93484. // Dont teleport if another gaze already requested teleportation
  93485. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93486. return;
  93487. }
  93488. if (!gazer._teleportationRequestInitiated) {
  93489. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93490. gazer._activatePointer();
  93491. gazer._teleportationRequestInitiated = true;
  93492. }
  93493. }
  93494. else {
  93495. // Listening to the proper controller values changes to confirm teleportation
  93496. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93497. if (this._teleportActive) {
  93498. this._teleportCamera(this._haloCenter);
  93499. }
  93500. gazer._teleportationRequestInitiated = false;
  93501. }
  93502. }
  93503. };
  93504. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93505. // Only rotate when user is not currently selecting a teleportation location
  93506. if (gazer._teleportationRequestInitiated) {
  93507. return;
  93508. }
  93509. if (!gazer._rotationLeftAsked) {
  93510. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93511. gazer._rotationLeftAsked = true;
  93512. if (this._rotationAllowed) {
  93513. this._rotateCamera(false);
  93514. }
  93515. }
  93516. }
  93517. else {
  93518. if (stateObject.x > -this._padSensibilityDown) {
  93519. gazer._rotationLeftAsked = false;
  93520. }
  93521. }
  93522. if (!gazer._rotationRightAsked) {
  93523. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93524. gazer._rotationRightAsked = true;
  93525. if (this._rotationAllowed) {
  93526. this._rotateCamera(true);
  93527. }
  93528. }
  93529. }
  93530. else {
  93531. if (stateObject.x < this._padSensibilityDown) {
  93532. gazer._rotationRightAsked = false;
  93533. }
  93534. }
  93535. };
  93536. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93537. // Only teleport backwards when user is not currently selecting a teleportation location
  93538. if (gazer._teleportationRequestInitiated) {
  93539. return;
  93540. }
  93541. // Teleport backwards
  93542. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93543. if (!gazer._teleportationBackRequestInitiated) {
  93544. if (!this.currentVRCamera) {
  93545. return;
  93546. }
  93547. // Get rotation and position of the current camera
  93548. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93549. var position = this.currentVRCamera.position;
  93550. // If the camera has device position, use that instead
  93551. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93552. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93553. position = this.currentVRCamera.devicePosition;
  93554. }
  93555. // Get matrix with only the y rotation of the device rotation
  93556. rotation.toEulerAnglesToRef(this._workingVector);
  93557. this._workingVector.z = 0;
  93558. this._workingVector.x = 0;
  93559. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93560. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93561. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93562. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93563. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93564. var ray = new BABYLON.Ray(position, this._workingVector);
  93565. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93566. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93567. this._teleportCamera(hit.pickedPoint);
  93568. }
  93569. gazer._teleportationBackRequestInitiated = true;
  93570. }
  93571. }
  93572. else {
  93573. gazer._teleportationBackRequestInitiated = false;
  93574. }
  93575. };
  93576. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93577. var _this = this;
  93578. var controllerMesh = controller.webVRController.mesh;
  93579. if (controllerMesh) {
  93580. if (!controller._interactionsEnabled) {
  93581. this._enableInteractionOnController(controller);
  93582. }
  93583. controller._interactionsEnabled = true;
  93584. controller._teleportationEnabled = true;
  93585. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93586. controller._dpadPressed = false;
  93587. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93588. controller._dpadPressed = stateObject.pressed;
  93589. if (!controller._dpadPressed) {
  93590. controller._rotationLeftAsked = false;
  93591. controller._rotationRightAsked = false;
  93592. controller._teleportationBackRequestInitiated = false;
  93593. }
  93594. });
  93595. }
  93596. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93597. if (_this.teleportationEnabled) {
  93598. _this._checkTeleportBackwards(stateObject, controller);
  93599. _this._checkTeleportWithRay(stateObject, controller);
  93600. }
  93601. _this._checkRotate(stateObject, controller);
  93602. });
  93603. }
  93604. };
  93605. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93606. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93607. this._teleportationTarget.isPickable = false;
  93608. var length = 512;
  93609. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93610. dynamicTexture.hasAlpha = true;
  93611. var context = dynamicTexture.getContext();
  93612. var centerX = length / 2;
  93613. var centerY = length / 2;
  93614. var radius = 200;
  93615. context.beginPath();
  93616. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93617. context.fillStyle = this._teleportationFillColor;
  93618. context.fill();
  93619. context.lineWidth = 10;
  93620. context.strokeStyle = this._teleportationBorderColor;
  93621. context.stroke();
  93622. context.closePath();
  93623. dynamicTexture.update();
  93624. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93625. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93626. this._teleportationTarget.material = teleportationCircleMaterial;
  93627. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93628. torus.isPickable = false;
  93629. torus.parent = this._teleportationTarget;
  93630. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93631. var keys = [];
  93632. keys.push({
  93633. frame: 0,
  93634. value: 0
  93635. });
  93636. keys.push({
  93637. frame: 30,
  93638. value: 0.4
  93639. });
  93640. keys.push({
  93641. frame: 60,
  93642. value: 0
  93643. });
  93644. animationInnerCircle.setKeys(keys);
  93645. var easingFunction = new BABYLON.SineEase();
  93646. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93647. animationInnerCircle.setEasingFunction(easingFunction);
  93648. torus.animations = [];
  93649. torus.animations.push(animationInnerCircle);
  93650. this._scene.beginAnimation(torus, 0, 60, true);
  93651. this._hideTeleportationTarget();
  93652. };
  93653. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93654. this._teleportActive = true;
  93655. if (this._teleportationInitialized) {
  93656. this._teleportationTarget.isVisible = true;
  93657. if (this._isDefaultTeleportationTarget) {
  93658. this._teleportationTarget.getChildren()[0].isVisible = true;
  93659. }
  93660. }
  93661. };
  93662. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93663. this._teleportActive = false;
  93664. if (this._teleportationInitialized) {
  93665. this._teleportationTarget.isVisible = false;
  93666. if (this._isDefaultTeleportationTarget) {
  93667. this._teleportationTarget.getChildren()[0].isVisible = false;
  93668. }
  93669. }
  93670. };
  93671. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93672. var _this = this;
  93673. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93674. return;
  93675. }
  93676. if (right) {
  93677. this._rotationAngle++;
  93678. }
  93679. else {
  93680. this._rotationAngle--;
  93681. }
  93682. this.currentVRCamera.animations = [];
  93683. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93684. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93685. var animationRotationKeys = [];
  93686. animationRotationKeys.push({
  93687. frame: 0,
  93688. value: this.currentVRCamera.rotationQuaternion
  93689. });
  93690. animationRotationKeys.push({
  93691. frame: 6,
  93692. value: target
  93693. });
  93694. animationRotation.setKeys(animationRotationKeys);
  93695. animationRotation.setEasingFunction(this._circleEase);
  93696. this.currentVRCamera.animations.push(animationRotation);
  93697. this._postProcessMove.animations = [];
  93698. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93699. var vignetteWeightKeys = [];
  93700. vignetteWeightKeys.push({
  93701. frame: 0,
  93702. value: 0
  93703. });
  93704. vignetteWeightKeys.push({
  93705. frame: 3,
  93706. value: 4
  93707. });
  93708. vignetteWeightKeys.push({
  93709. frame: 6,
  93710. value: 0
  93711. });
  93712. animationPP.setKeys(vignetteWeightKeys);
  93713. animationPP.setEasingFunction(this._circleEase);
  93714. this._postProcessMove.animations.push(animationPP);
  93715. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93716. var vignetteStretchKeys = [];
  93717. vignetteStretchKeys.push({
  93718. frame: 0,
  93719. value: 0
  93720. });
  93721. vignetteStretchKeys.push({
  93722. frame: 3,
  93723. value: 10
  93724. });
  93725. vignetteStretchKeys.push({
  93726. frame: 6,
  93727. value: 0
  93728. });
  93729. animationPP2.setKeys(vignetteStretchKeys);
  93730. animationPP2.setEasingFunction(this._circleEase);
  93731. this._postProcessMove.animations.push(animationPP2);
  93732. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93733. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93734. this._postProcessMove.samples = 4;
  93735. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93736. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93737. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93738. });
  93739. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93740. };
  93741. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93742. if (hit.pickedPoint) {
  93743. if (gazer._teleportationRequestInitiated) {
  93744. this._displayTeleportationTarget();
  93745. this._haloCenter.copyFrom(hit.pickedPoint);
  93746. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93747. }
  93748. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93749. if (pickNormal) {
  93750. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93751. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93752. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93753. }
  93754. this._teleportationTarget.position.y += 0.1;
  93755. }
  93756. };
  93757. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93758. var _this = this;
  93759. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93760. return;
  93761. }
  93762. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93763. // offset of the headset from the anchor.
  93764. if (this.webVRCamera.leftCamera) {
  93765. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93766. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93767. location.subtractToRef(this._workingVector, this._workingVector);
  93768. }
  93769. else {
  93770. this._workingVector.copyFrom(location);
  93771. }
  93772. // Add height to account for user's height offset
  93773. if (this.isInVRMode) {
  93774. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93775. }
  93776. else {
  93777. this._workingVector.y += this._defaultHeight;
  93778. }
  93779. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93780. // Create animation from the camera's position to the new location
  93781. this.currentVRCamera.animations = [];
  93782. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93783. var animationCameraTeleportationKeys = [{
  93784. frame: 0,
  93785. value: this.currentVRCamera.position
  93786. },
  93787. {
  93788. frame: 11,
  93789. value: this._workingVector
  93790. }
  93791. ];
  93792. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93793. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93794. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93795. this._postProcessMove.animations = [];
  93796. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93797. var vignetteWeightKeys = [];
  93798. vignetteWeightKeys.push({
  93799. frame: 0,
  93800. value: 0
  93801. });
  93802. vignetteWeightKeys.push({
  93803. frame: 5,
  93804. value: 8
  93805. });
  93806. vignetteWeightKeys.push({
  93807. frame: 11,
  93808. value: 0
  93809. });
  93810. animationPP.setKeys(vignetteWeightKeys);
  93811. this._postProcessMove.animations.push(animationPP);
  93812. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93813. var vignetteStretchKeys = [];
  93814. vignetteStretchKeys.push({
  93815. frame: 0,
  93816. value: 0
  93817. });
  93818. vignetteStretchKeys.push({
  93819. frame: 5,
  93820. value: 10
  93821. });
  93822. vignetteStretchKeys.push({
  93823. frame: 11,
  93824. value: 0
  93825. });
  93826. animationPP2.setKeys(vignetteStretchKeys);
  93827. this._postProcessMove.animations.push(animationPP2);
  93828. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93829. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93830. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93831. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93832. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93833. });
  93834. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93835. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93836. });
  93837. this._hideTeleportationTarget();
  93838. };
  93839. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93840. if (normal) {
  93841. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93842. if (angle < Math.PI / 2) {
  93843. normal.scaleInPlace(-1);
  93844. }
  93845. }
  93846. return normal;
  93847. };
  93848. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93849. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93850. return;
  93851. }
  93852. var ray = gazer._getForwardRay(this._rayLength);
  93853. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93854. if (hit) {
  93855. // Populate the contrllers mesh that can be used for drag/drop
  93856. if (gazer._laserPointer) {
  93857. hit.originMesh = gazer._laserPointer.parent;
  93858. }
  93859. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93860. }
  93861. gazer._currentHit = hit;
  93862. // Moving the gazeTracker on the mesh face targetted
  93863. if (hit && hit.pickedPoint) {
  93864. if (this._displayGaze) {
  93865. var multiplier = 1;
  93866. gazer._gazeTracker.isVisible = true;
  93867. if (gazer._isActionableMesh) {
  93868. multiplier = 3;
  93869. }
  93870. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93871. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93872. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93873. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93874. // To avoid z-fighting
  93875. var deltaFighting = 0.002;
  93876. if (pickNormal) {
  93877. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93878. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93879. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93880. }
  93881. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93882. if (gazer._gazeTracker.position.x < 0) {
  93883. gazer._gazeTracker.position.x += deltaFighting;
  93884. }
  93885. else {
  93886. gazer._gazeTracker.position.x -= deltaFighting;
  93887. }
  93888. if (gazer._gazeTracker.position.y < 0) {
  93889. gazer._gazeTracker.position.y += deltaFighting;
  93890. }
  93891. else {
  93892. gazer._gazeTracker.position.y -= deltaFighting;
  93893. }
  93894. if (gazer._gazeTracker.position.z < 0) {
  93895. gazer._gazeTracker.position.z += deltaFighting;
  93896. }
  93897. else {
  93898. gazer._gazeTracker.position.z -= deltaFighting;
  93899. }
  93900. }
  93901. // Changing the size of the laser pointer based on the distance from the targetted point
  93902. gazer._updatePointerDistance(hit.distance);
  93903. }
  93904. else {
  93905. gazer._updatePointerDistance();
  93906. gazer._gazeTracker.isVisible = false;
  93907. }
  93908. if (hit && hit.pickedMesh) {
  93909. // The object selected is the floor, we're in a teleportation scenario
  93910. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93911. // Moving the teleportation area to this targetted point
  93912. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93913. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93914. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93915. }
  93916. gazer._currentMeshSelected = null;
  93917. if (gazer._teleportationRequestInitiated) {
  93918. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93919. }
  93920. return;
  93921. }
  93922. // If not, we're in a selection scenario
  93923. //this._teleportationAllowed = false;
  93924. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93925. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93926. this.onNewMeshPicked.notifyObservers(hit);
  93927. gazer._currentMeshSelected = hit.pickedMesh;
  93928. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93929. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93930. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93931. gazer._isActionableMesh = true;
  93932. }
  93933. else {
  93934. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93935. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93936. gazer._isActionableMesh = false;
  93937. }
  93938. try {
  93939. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93940. }
  93941. catch (err) {
  93942. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93943. }
  93944. }
  93945. else {
  93946. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93947. gazer._currentMeshSelected = null;
  93948. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93949. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93950. }
  93951. }
  93952. }
  93953. else {
  93954. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93955. gazer._currentMeshSelected = null;
  93956. //this._teleportationAllowed = false;
  93957. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93958. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93959. }
  93960. };
  93961. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93962. if (mesh) {
  93963. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93964. }
  93965. };
  93966. /**
  93967. * Sets the color of the laser ray from the vr controllers.
  93968. * @param color new color for the ray.
  93969. */
  93970. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93971. if (this.leftController) {
  93972. this.leftController._setLaserPointerColor(color);
  93973. }
  93974. if (this.rightController) {
  93975. this.rightController._setLaserPointerColor(color);
  93976. }
  93977. };
  93978. /**
  93979. * Sets the color of the ray from the vr headsets gaze.
  93980. * @param color new color for the ray.
  93981. */
  93982. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93983. if (!this._cameraGazer._gazeTracker.material) {
  93984. return;
  93985. }
  93986. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93987. if (this.leftController) {
  93988. this.leftController._gazeTracker.material.emissiveColor = color;
  93989. }
  93990. if (this.rightController) {
  93991. this.rightController._gazeTracker.material.emissiveColor = color;
  93992. }
  93993. };
  93994. /**
  93995. * Exits VR and disposes of the vr experience helper
  93996. */
  93997. VRExperienceHelper.prototype.dispose = function () {
  93998. if (this.isInVRMode) {
  93999. this.exitVR();
  94000. }
  94001. if (this._postProcessMove) {
  94002. this._postProcessMove.dispose();
  94003. }
  94004. if (this._webVRCamera) {
  94005. this._webVRCamera.dispose();
  94006. }
  94007. if (this._vrDeviceOrientationCamera) {
  94008. this._vrDeviceOrientationCamera.dispose();
  94009. }
  94010. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94011. document.body.removeChild(this._btnVR);
  94012. }
  94013. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94014. this._deviceOrientationCamera.dispose();
  94015. }
  94016. if (this._cameraGazer) {
  94017. this._cameraGazer.dispose();
  94018. }
  94019. if (this.leftController) {
  94020. this.leftController.dispose();
  94021. }
  94022. if (this.rightController) {
  94023. this.rightController.dispose();
  94024. }
  94025. if (this._teleportationTarget) {
  94026. this._teleportationTarget.dispose();
  94027. }
  94028. this._floorMeshesCollection = [];
  94029. document.removeEventListener("keydown", this._onKeyDown);
  94030. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94031. window.removeEventListener("resize", this._onResize);
  94032. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94033. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94034. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94035. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94036. document.onmsfullscreenchange = null;
  94037. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94038. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94039. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94040. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94041. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94042. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94043. this._scene.unregisterBeforeRender(this.beforeRender);
  94044. };
  94045. /**
  94046. * Gets the name of the VRExperienceHelper class
  94047. * @returns "VRExperienceHelper"
  94048. */
  94049. VRExperienceHelper.prototype.getClassName = function () {
  94050. return "VRExperienceHelper";
  94051. };
  94052. return VRExperienceHelper;
  94053. }());
  94054. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94055. })(BABYLON || (BABYLON = {}));
  94056. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94057. // Mainly based on these 2 articles :
  94058. // 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
  94059. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94060. var BABYLON;
  94061. (function (BABYLON) {
  94062. /**
  94063. * Defines the potential axis of a Joystick
  94064. */
  94065. var JoystickAxis;
  94066. (function (JoystickAxis) {
  94067. /** X axis */
  94068. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94069. /** Y axis */
  94070. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94071. /** Z axis */
  94072. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94073. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94074. /**
  94075. * Class used to define virtual joystick (used in touch mode)
  94076. */
  94077. var VirtualJoystick = /** @class */ (function () {
  94078. /**
  94079. * Creates a new virtual joystick
  94080. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94081. */
  94082. function VirtualJoystick(leftJoystick) {
  94083. var _this = this;
  94084. if (leftJoystick) {
  94085. this._leftJoystick = true;
  94086. }
  94087. else {
  94088. this._leftJoystick = false;
  94089. }
  94090. VirtualJoystick._globalJoystickIndex++;
  94091. // By default left & right arrow keys are moving the X
  94092. // and up & down keys are moving the Y
  94093. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94094. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94095. this.reverseLeftRight = false;
  94096. this.reverseUpDown = false;
  94097. // collections of pointers
  94098. this._touches = new BABYLON.StringDictionary();
  94099. this.deltaPosition = BABYLON.Vector3.Zero();
  94100. this._joystickSensibility = 25;
  94101. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94102. this._onResize = function (evt) {
  94103. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94104. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94105. if (VirtualJoystick.vjCanvas) {
  94106. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94107. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94108. }
  94109. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94110. };
  94111. // injecting a canvas element on top of the canvas 3D game
  94112. if (!VirtualJoystick.vjCanvas) {
  94113. window.addEventListener("resize", this._onResize, false);
  94114. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94115. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94116. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94117. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94118. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94119. VirtualJoystick.vjCanvas.style.width = "100%";
  94120. VirtualJoystick.vjCanvas.style.height = "100%";
  94121. VirtualJoystick.vjCanvas.style.position = "absolute";
  94122. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94123. VirtualJoystick.vjCanvas.style.top = "0px";
  94124. VirtualJoystick.vjCanvas.style.left = "0px";
  94125. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94126. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94127. // Support for jQuery PEP polyfill
  94128. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94129. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94130. if (!context) {
  94131. throw new Error("Unable to create canvas for virtual joystick");
  94132. }
  94133. VirtualJoystick.vjCanvasContext = context;
  94134. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94135. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94136. document.body.appendChild(VirtualJoystick.vjCanvas);
  94137. }
  94138. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94139. this.pressed = false;
  94140. // default joystick color
  94141. this._joystickColor = "cyan";
  94142. this._joystickPointerID = -1;
  94143. // current joystick position
  94144. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94145. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94146. // origin joystick position
  94147. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94148. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94149. this._onPointerDownHandlerRef = function (evt) {
  94150. _this._onPointerDown(evt);
  94151. };
  94152. this._onPointerMoveHandlerRef = function (evt) {
  94153. _this._onPointerMove(evt);
  94154. };
  94155. this._onPointerUpHandlerRef = function (evt) {
  94156. _this._onPointerUp(evt);
  94157. };
  94158. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94159. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94160. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94161. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94162. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94163. evt.preventDefault(); // Disables system menu
  94164. }, false);
  94165. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94166. }
  94167. /**
  94168. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94169. * @param newJoystickSensibility defines the new sensibility
  94170. */
  94171. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94172. this._joystickSensibility = newJoystickSensibility;
  94173. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94174. };
  94175. VirtualJoystick.prototype._onPointerDown = function (e) {
  94176. var positionOnScreenCondition;
  94177. e.preventDefault();
  94178. if (this._leftJoystick === true) {
  94179. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94180. }
  94181. else {
  94182. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94183. }
  94184. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94185. // First contact will be dedicated to the virtual joystick
  94186. this._joystickPointerID = e.pointerId;
  94187. this._joystickPointerStartPos.x = e.clientX;
  94188. this._joystickPointerStartPos.y = e.clientY;
  94189. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94190. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94191. this._deltaJoystickVector.x = 0;
  94192. this._deltaJoystickVector.y = 0;
  94193. this.pressed = true;
  94194. this._touches.add(e.pointerId.toString(), e);
  94195. }
  94196. else {
  94197. // You can only trigger the action buttons with a joystick declared
  94198. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94199. this._action();
  94200. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94201. }
  94202. }
  94203. };
  94204. VirtualJoystick.prototype._onPointerMove = function (e) {
  94205. // If the current pointer is the one associated to the joystick (first touch contact)
  94206. if (this._joystickPointerID == e.pointerId) {
  94207. this._joystickPointerPos.x = e.clientX;
  94208. this._joystickPointerPos.y = e.clientY;
  94209. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94210. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94211. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94212. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94213. switch (this._axisTargetedByLeftAndRight) {
  94214. case JoystickAxis.X:
  94215. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94216. break;
  94217. case JoystickAxis.Y:
  94218. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94219. break;
  94220. case JoystickAxis.Z:
  94221. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94222. break;
  94223. }
  94224. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94225. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94226. switch (this._axisTargetedByUpAndDown) {
  94227. case JoystickAxis.X:
  94228. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94229. break;
  94230. case JoystickAxis.Y:
  94231. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94232. break;
  94233. case JoystickAxis.Z:
  94234. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94235. break;
  94236. }
  94237. }
  94238. else {
  94239. var data = this._touches.get(e.pointerId.toString());
  94240. if (data) {
  94241. data.x = e.clientX;
  94242. data.y = e.clientY;
  94243. }
  94244. }
  94245. };
  94246. VirtualJoystick.prototype._onPointerUp = function (e) {
  94247. if (this._joystickPointerID == e.pointerId) {
  94248. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94249. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94250. this._joystickPointerID = -1;
  94251. this.pressed = false;
  94252. }
  94253. else {
  94254. var touch = this._touches.get(e.pointerId.toString());
  94255. if (touch) {
  94256. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94257. }
  94258. }
  94259. this._deltaJoystickVector.x = 0;
  94260. this._deltaJoystickVector.y = 0;
  94261. this._touches.remove(e.pointerId.toString());
  94262. };
  94263. /**
  94264. * Change the color of the virtual joystick
  94265. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94266. */
  94267. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94268. this._joystickColor = newColor;
  94269. };
  94270. /**
  94271. * Defines a callback to call when the joystick is touched
  94272. * @param action defines the callback
  94273. */
  94274. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94275. this._action = action;
  94276. };
  94277. /**
  94278. * Defines which axis you'd like to control for left & right
  94279. * @param axis defines the axis to use
  94280. */
  94281. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94282. switch (axis) {
  94283. case JoystickAxis.X:
  94284. case JoystickAxis.Y:
  94285. case JoystickAxis.Z:
  94286. this._axisTargetedByLeftAndRight = axis;
  94287. break;
  94288. default:
  94289. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94290. break;
  94291. }
  94292. };
  94293. /**
  94294. * Defines which axis you'd like to control for up & down
  94295. * @param axis defines the axis to use
  94296. */
  94297. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94298. switch (axis) {
  94299. case JoystickAxis.X:
  94300. case JoystickAxis.Y:
  94301. case JoystickAxis.Z:
  94302. this._axisTargetedByUpAndDown = axis;
  94303. break;
  94304. default:
  94305. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94306. break;
  94307. }
  94308. };
  94309. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94310. var _this = this;
  94311. if (this.pressed) {
  94312. this._touches.forEach(function (key, touch) {
  94313. if (touch.pointerId === _this._joystickPointerID) {
  94314. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94315. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94316. VirtualJoystick.vjCanvasContext.beginPath();
  94317. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94318. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94319. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94320. VirtualJoystick.vjCanvasContext.stroke();
  94321. VirtualJoystick.vjCanvasContext.closePath();
  94322. VirtualJoystick.vjCanvasContext.beginPath();
  94323. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94324. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94325. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94326. VirtualJoystick.vjCanvasContext.stroke();
  94327. VirtualJoystick.vjCanvasContext.closePath();
  94328. VirtualJoystick.vjCanvasContext.beginPath();
  94329. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94330. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94331. VirtualJoystick.vjCanvasContext.stroke();
  94332. VirtualJoystick.vjCanvasContext.closePath();
  94333. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94334. }
  94335. else {
  94336. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94337. VirtualJoystick.vjCanvasContext.beginPath();
  94338. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94339. VirtualJoystick.vjCanvasContext.beginPath();
  94340. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94341. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94342. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94343. VirtualJoystick.vjCanvasContext.stroke();
  94344. VirtualJoystick.vjCanvasContext.closePath();
  94345. touch.prevX = touch.x;
  94346. touch.prevY = touch.y;
  94347. }
  94348. ;
  94349. });
  94350. }
  94351. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94352. };
  94353. /**
  94354. * Release internal HTML canvas
  94355. */
  94356. VirtualJoystick.prototype.releaseCanvas = function () {
  94357. if (VirtualJoystick.vjCanvas) {
  94358. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94359. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94360. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94361. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94362. window.removeEventListener("resize", this._onResize);
  94363. document.body.removeChild(VirtualJoystick.vjCanvas);
  94364. VirtualJoystick.vjCanvas = null;
  94365. }
  94366. };
  94367. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94368. VirtualJoystick._globalJoystickIndex = 0;
  94369. return VirtualJoystick;
  94370. }());
  94371. BABYLON.VirtualJoystick = VirtualJoystick;
  94372. })(BABYLON || (BABYLON = {}));
  94373. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94374. var BABYLON;
  94375. (function (BABYLON) {
  94376. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94377. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94378. });
  94379. // We're mainly based on the logic defined into the FreeCamera code
  94380. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94381. __extends(VirtualJoysticksCamera, _super);
  94382. function VirtualJoysticksCamera(name, position, scene) {
  94383. var _this = _super.call(this, name, position, scene) || this;
  94384. _this.inputs.addVirtualJoystick();
  94385. return _this;
  94386. }
  94387. VirtualJoysticksCamera.prototype.getClassName = function () {
  94388. return "VirtualJoysticksCamera";
  94389. };
  94390. return VirtualJoysticksCamera;
  94391. }(BABYLON.FreeCamera));
  94392. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94393. })(BABYLON || (BABYLON = {}));
  94394. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94395. var BABYLON;
  94396. (function (BABYLON) {
  94397. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94398. function FreeCameraVirtualJoystickInput() {
  94399. }
  94400. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94401. return this._leftjoystick;
  94402. };
  94403. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94404. return this._rightjoystick;
  94405. };
  94406. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94407. if (this._leftjoystick) {
  94408. var camera = this.camera;
  94409. var speed = camera._computeLocalCameraSpeed() * 50;
  94410. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94411. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94412. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94413. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94414. if (!this._leftjoystick.pressed) {
  94415. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94416. }
  94417. if (!this._rightjoystick.pressed) {
  94418. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94419. }
  94420. }
  94421. };
  94422. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94423. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94424. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94425. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94426. this._leftjoystick.setJoystickSensibility(0.15);
  94427. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94428. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94429. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94430. this._rightjoystick.reverseUpDown = true;
  94431. this._rightjoystick.setJoystickSensibility(0.05);
  94432. this._rightjoystick.setJoystickColor("yellow");
  94433. };
  94434. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94435. this._leftjoystick.releaseCanvas();
  94436. this._rightjoystick.releaseCanvas();
  94437. };
  94438. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94439. return "FreeCameraVirtualJoystickInput";
  94440. };
  94441. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94442. return "virtualJoystick";
  94443. };
  94444. return FreeCameraVirtualJoystickInput;
  94445. }());
  94446. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94447. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94448. })(BABYLON || (BABYLON = {}));
  94449. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94450. var BABYLON;
  94451. (function (BABYLON) {
  94452. var SimplificationSettings = /** @class */ (function () {
  94453. function SimplificationSettings(quality, distance, optimizeMesh) {
  94454. this.quality = quality;
  94455. this.distance = distance;
  94456. this.optimizeMesh = optimizeMesh;
  94457. }
  94458. return SimplificationSettings;
  94459. }());
  94460. BABYLON.SimplificationSettings = SimplificationSettings;
  94461. var SimplificationQueue = /** @class */ (function () {
  94462. function SimplificationQueue() {
  94463. this.running = false;
  94464. this._simplificationArray = [];
  94465. }
  94466. SimplificationQueue.prototype.addTask = function (task) {
  94467. this._simplificationArray.push(task);
  94468. };
  94469. SimplificationQueue.prototype.executeNext = function () {
  94470. var task = this._simplificationArray.pop();
  94471. if (task) {
  94472. this.running = true;
  94473. this.runSimplification(task);
  94474. }
  94475. else {
  94476. this.running = false;
  94477. }
  94478. };
  94479. SimplificationQueue.prototype.runSimplification = function (task) {
  94480. var _this = this;
  94481. if (task.parallelProcessing) {
  94482. //parallel simplifier
  94483. task.settings.forEach(function (setting) {
  94484. var simplifier = _this.getSimplifier(task);
  94485. simplifier.simplify(setting, function (newMesh) {
  94486. task.mesh.addLODLevel(setting.distance, newMesh);
  94487. newMesh.isVisible = true;
  94488. //check if it is the last
  94489. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94490. //all done, run the success callback.
  94491. task.successCallback();
  94492. }
  94493. _this.executeNext();
  94494. });
  94495. });
  94496. }
  94497. else {
  94498. //single simplifier.
  94499. var simplifier = this.getSimplifier(task);
  94500. var runDecimation = function (setting, callback) {
  94501. simplifier.simplify(setting, function (newMesh) {
  94502. task.mesh.addLODLevel(setting.distance, newMesh);
  94503. newMesh.isVisible = true;
  94504. //run the next quality level
  94505. callback();
  94506. });
  94507. };
  94508. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94509. runDecimation(task.settings[loop.index], function () {
  94510. loop.executeNext();
  94511. });
  94512. }, function () {
  94513. //execution ended, run the success callback.
  94514. if (task.successCallback) {
  94515. task.successCallback();
  94516. }
  94517. _this.executeNext();
  94518. });
  94519. }
  94520. };
  94521. SimplificationQueue.prototype.getSimplifier = function (task) {
  94522. switch (task.simplificationType) {
  94523. case SimplificationType.QUADRATIC:
  94524. default:
  94525. return new QuadraticErrorSimplification(task.mesh);
  94526. }
  94527. };
  94528. return SimplificationQueue;
  94529. }());
  94530. BABYLON.SimplificationQueue = SimplificationQueue;
  94531. /**
  94532. * The implemented types of simplification
  94533. * At the moment only Quadratic Error Decimation is implemented
  94534. */
  94535. var SimplificationType;
  94536. (function (SimplificationType) {
  94537. /** Quadratic error decimation */
  94538. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94539. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94540. var DecimationTriangle = /** @class */ (function () {
  94541. function DecimationTriangle(vertices) {
  94542. this.vertices = vertices;
  94543. this.error = new Array(4);
  94544. this.deleted = false;
  94545. this.isDirty = false;
  94546. this.deletePending = false;
  94547. this.borderFactor = 0;
  94548. }
  94549. return DecimationTriangle;
  94550. }());
  94551. BABYLON.DecimationTriangle = DecimationTriangle;
  94552. var DecimationVertex = /** @class */ (function () {
  94553. function DecimationVertex(position, id) {
  94554. this.position = position;
  94555. this.id = id;
  94556. this.isBorder = true;
  94557. this.q = new QuadraticMatrix();
  94558. this.triangleCount = 0;
  94559. this.triangleStart = 0;
  94560. this.originalOffsets = [];
  94561. }
  94562. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94563. this.position.copyFrom(newPosition);
  94564. };
  94565. return DecimationVertex;
  94566. }());
  94567. BABYLON.DecimationVertex = DecimationVertex;
  94568. var QuadraticMatrix = /** @class */ (function () {
  94569. function QuadraticMatrix(data) {
  94570. this.data = new Array(10);
  94571. for (var i = 0; i < 10; ++i) {
  94572. if (data && data[i]) {
  94573. this.data[i] = data[i];
  94574. }
  94575. else {
  94576. this.data[i] = 0;
  94577. }
  94578. }
  94579. }
  94580. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94581. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94582. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94583. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94584. return det;
  94585. };
  94586. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94587. for (var i = 0; i < 10; ++i) {
  94588. this.data[i] += matrix.data[i];
  94589. }
  94590. };
  94591. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94592. for (var i = 0; i < 10; ++i) {
  94593. this.data[i] += data[i];
  94594. }
  94595. };
  94596. QuadraticMatrix.prototype.add = function (matrix) {
  94597. var m = new QuadraticMatrix();
  94598. for (var i = 0; i < 10; ++i) {
  94599. m.data[i] = this.data[i] + matrix.data[i];
  94600. }
  94601. return m;
  94602. };
  94603. QuadraticMatrix.FromData = function (a, b, c, d) {
  94604. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94605. };
  94606. //returning an array to avoid garbage collection
  94607. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94608. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94609. };
  94610. return QuadraticMatrix;
  94611. }());
  94612. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94613. var Reference = /** @class */ (function () {
  94614. function Reference(vertexId, triangleId) {
  94615. this.vertexId = vertexId;
  94616. this.triangleId = triangleId;
  94617. }
  94618. return Reference;
  94619. }());
  94620. BABYLON.Reference = Reference;
  94621. /**
  94622. * An implementation of the Quadratic Error simplification algorithm.
  94623. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94624. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94625. * @author RaananW
  94626. */
  94627. var QuadraticErrorSimplification = /** @class */ (function () {
  94628. function QuadraticErrorSimplification(_mesh) {
  94629. this._mesh = _mesh;
  94630. this.syncIterations = 5000;
  94631. this.aggressiveness = 7;
  94632. this.decimationIterations = 100;
  94633. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94634. }
  94635. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94636. var _this = this;
  94637. this.initDecimatedMesh();
  94638. //iterating through the submeshes array, one after the other.
  94639. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94640. _this.initWithMesh(loop.index, function () {
  94641. _this.runDecimation(settings, loop.index, function () {
  94642. loop.executeNext();
  94643. });
  94644. }, settings.optimizeMesh);
  94645. }, function () {
  94646. setTimeout(function () {
  94647. successCallback(_this._reconstructedMesh);
  94648. }, 0);
  94649. });
  94650. };
  94651. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94652. var _this = this;
  94653. var targetCount = ~~(this.triangles.length * settings.quality);
  94654. var deletedTriangles = 0;
  94655. var triangleCount = this.triangles.length;
  94656. var iterationFunction = function (iteration, callback) {
  94657. setTimeout(function () {
  94658. if (iteration % 5 === 0) {
  94659. _this.updateMesh(iteration === 0);
  94660. }
  94661. for (var i = 0; i < _this.triangles.length; ++i) {
  94662. _this.triangles[i].isDirty = false;
  94663. }
  94664. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94665. var trianglesIterator = function (i) {
  94666. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94667. var t = _this.triangles[tIdx];
  94668. if (!t)
  94669. return;
  94670. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94671. return;
  94672. }
  94673. for (var j = 0; j < 3; ++j) {
  94674. if (t.error[j] < threshold) {
  94675. var deleted0 = [];
  94676. var deleted1 = [];
  94677. var v0 = t.vertices[j];
  94678. var v1 = t.vertices[(j + 1) % 3];
  94679. if (v0.isBorder || v1.isBorder)
  94680. continue;
  94681. var p = BABYLON.Vector3.Zero();
  94682. var n = BABYLON.Vector3.Zero();
  94683. var uv = BABYLON.Vector2.Zero();
  94684. var color = new BABYLON.Color4(0, 0, 0, 1);
  94685. _this.calculateError(v0, v1, p, n, uv, color);
  94686. var delTr = new Array();
  94687. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94688. continue;
  94689. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94690. continue;
  94691. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94692. continue;
  94693. var uniqueArray = new Array();
  94694. delTr.forEach(function (deletedT) {
  94695. if (uniqueArray.indexOf(deletedT) === -1) {
  94696. deletedT.deletePending = true;
  94697. uniqueArray.push(deletedT);
  94698. }
  94699. });
  94700. if (uniqueArray.length % 2 !== 0) {
  94701. continue;
  94702. }
  94703. v0.q = v1.q.add(v0.q);
  94704. v0.updatePosition(p);
  94705. var tStart = _this.references.length;
  94706. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94707. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94708. var tCount = _this.references.length - tStart;
  94709. if (tCount <= v0.triangleCount) {
  94710. if (tCount) {
  94711. for (var c = 0; c < tCount; c++) {
  94712. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94713. }
  94714. }
  94715. }
  94716. else {
  94717. v0.triangleStart = tStart;
  94718. }
  94719. v0.triangleCount = tCount;
  94720. break;
  94721. }
  94722. }
  94723. };
  94724. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94725. }, 0);
  94726. };
  94727. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94728. if (triangleCount - deletedTriangles <= targetCount)
  94729. loop.breakLoop();
  94730. else {
  94731. iterationFunction(loop.index, function () {
  94732. loop.executeNext();
  94733. });
  94734. }
  94735. }, function () {
  94736. setTimeout(function () {
  94737. //reconstruct this part of the mesh
  94738. _this.reconstructMesh(submeshIndex);
  94739. successCallback();
  94740. }, 0);
  94741. });
  94742. };
  94743. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94744. var _this = this;
  94745. this.vertices = [];
  94746. this.triangles = [];
  94747. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94748. var indices = this._mesh.getIndices();
  94749. var submesh = this._mesh.subMeshes[submeshIndex];
  94750. var findInVertices = function (positionToSearch) {
  94751. if (optimizeMesh) {
  94752. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94753. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94754. return _this.vertices[ii];
  94755. }
  94756. }
  94757. }
  94758. return null;
  94759. };
  94760. var vertexReferences = [];
  94761. var vertexInit = function (i) {
  94762. if (!positionData) {
  94763. return;
  94764. }
  94765. var offset = i + submesh.verticesStart;
  94766. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94767. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94768. vertex.originalOffsets.push(offset);
  94769. if (vertex.id === _this.vertices.length) {
  94770. _this.vertices.push(vertex);
  94771. }
  94772. vertexReferences.push(vertex.id);
  94773. };
  94774. //var totalVertices = mesh.getTotalVertices();
  94775. var totalVertices = submesh.verticesCount;
  94776. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94777. var indicesInit = function (i) {
  94778. if (!indices) {
  94779. return;
  94780. }
  94781. var offset = (submesh.indexStart / 3) + i;
  94782. var pos = (offset * 3);
  94783. var i0 = indices[pos + 0];
  94784. var i1 = indices[pos + 1];
  94785. var i2 = indices[pos + 2];
  94786. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94787. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94788. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94789. var triangle = new DecimationTriangle([v0, v1, v2]);
  94790. triangle.originalOffset = pos;
  94791. _this.triangles.push(triangle);
  94792. };
  94793. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94794. _this.init(callback);
  94795. });
  94796. });
  94797. };
  94798. QuadraticErrorSimplification.prototype.init = function (callback) {
  94799. var _this = this;
  94800. var triangleInit1 = function (i) {
  94801. var t = _this.triangles[i];
  94802. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94803. for (var j = 0; j < 3; j++) {
  94804. 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))));
  94805. }
  94806. };
  94807. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94808. var triangleInit2 = function (i) {
  94809. var t = _this.triangles[i];
  94810. for (var j = 0; j < 3; ++j) {
  94811. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94812. }
  94813. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94814. };
  94815. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94816. callback();
  94817. });
  94818. });
  94819. };
  94820. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94821. var newTriangles = [];
  94822. var i;
  94823. for (i = 0; i < this.vertices.length; ++i) {
  94824. this.vertices[i].triangleCount = 0;
  94825. }
  94826. var t;
  94827. var j;
  94828. for (i = 0; i < this.triangles.length; ++i) {
  94829. if (!this.triangles[i].deleted) {
  94830. t = this.triangles[i];
  94831. for (j = 0; j < 3; ++j) {
  94832. t.vertices[j].triangleCount = 1;
  94833. }
  94834. newTriangles.push(t);
  94835. }
  94836. }
  94837. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94838. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94839. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94840. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94841. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94842. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94843. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94844. var vertexCount = 0;
  94845. for (i = 0; i < this.vertices.length; ++i) {
  94846. var vertex = this.vertices[i];
  94847. vertex.id = vertexCount;
  94848. if (vertex.triangleCount) {
  94849. vertex.originalOffsets.forEach(function (originalOffset) {
  94850. if (!normalData) {
  94851. return;
  94852. }
  94853. newPositionData.push(vertex.position.x);
  94854. newPositionData.push(vertex.position.y);
  94855. newPositionData.push(vertex.position.z);
  94856. newNormalData.push(normalData[originalOffset * 3]);
  94857. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94858. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94859. if (uvs && uvs.length) {
  94860. newUVsData.push(uvs[(originalOffset * 2)]);
  94861. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94862. }
  94863. else if (colorsData && colorsData.length) {
  94864. newColorsData.push(colorsData[(originalOffset * 4)]);
  94865. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94866. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94867. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94868. }
  94869. ++vertexCount;
  94870. });
  94871. }
  94872. }
  94873. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94874. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94875. var submeshesArray = this._reconstructedMesh.subMeshes;
  94876. this._reconstructedMesh.subMeshes = [];
  94877. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94878. var originalIndices = this._mesh.getIndices();
  94879. for (i = 0; i < newTriangles.length; ++i) {
  94880. t = newTriangles[i]; //now get the new referencing point for each vertex
  94881. [0, 1, 2].forEach(function (idx) {
  94882. var id = originalIndices[t.originalOffset + idx];
  94883. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94884. if (offset < 0)
  94885. offset = 0;
  94886. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94887. });
  94888. }
  94889. //overwriting the old vertex buffers and indices.
  94890. this._reconstructedMesh.setIndices(newIndicesArray);
  94891. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94892. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94893. if (newUVsData.length > 0)
  94894. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94895. if (newColorsData.length > 0)
  94896. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94897. //create submesh
  94898. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94899. if (submeshIndex > 0) {
  94900. this._reconstructedMesh.subMeshes = [];
  94901. submeshesArray.forEach(function (submesh) {
  94902. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94903. });
  94904. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94905. }
  94906. };
  94907. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94908. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94909. this._reconstructedMesh.material = this._mesh.material;
  94910. this._reconstructedMesh.parent = this._mesh.parent;
  94911. this._reconstructedMesh.isVisible = false;
  94912. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94913. };
  94914. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94915. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94916. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94917. if (t.deleted)
  94918. continue;
  94919. var s = this.references[vertex1.triangleStart + i].vertexId;
  94920. var v1 = t.vertices[(s + 1) % 3];
  94921. var v2 = t.vertices[(s + 2) % 3];
  94922. if ((v1 === vertex2 || v2 === vertex2)) {
  94923. deletedArray[i] = true;
  94924. delTr.push(t);
  94925. continue;
  94926. }
  94927. var d1 = v1.position.subtract(point);
  94928. d1 = d1.normalize();
  94929. var d2 = v2.position.subtract(point);
  94930. d2 = d2.normalize();
  94931. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94932. return true;
  94933. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94934. deletedArray[i] = false;
  94935. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94936. return true;
  94937. }
  94938. return false;
  94939. };
  94940. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94941. var newDeleted = deletedTriangles;
  94942. for (var i = 0; i < vertex.triangleCount; ++i) {
  94943. var ref = this.references[vertex.triangleStart + i];
  94944. var t = this.triangles[ref.triangleId];
  94945. if (t.deleted)
  94946. continue;
  94947. if (deletedArray[i] && t.deletePending) {
  94948. t.deleted = true;
  94949. newDeleted++;
  94950. continue;
  94951. }
  94952. t.vertices[ref.vertexId] = origVertex;
  94953. t.isDirty = true;
  94954. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94955. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94956. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94957. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94958. this.references.push(ref);
  94959. }
  94960. return newDeleted;
  94961. };
  94962. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94963. for (var i = 0; i < this.vertices.length; ++i) {
  94964. var vCount = [];
  94965. var vId = [];
  94966. var v = this.vertices[i];
  94967. var j;
  94968. for (j = 0; j < v.triangleCount; ++j) {
  94969. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94970. for (var ii = 0; ii < 3; ii++) {
  94971. var ofs = 0;
  94972. var vv = triangle.vertices[ii];
  94973. while (ofs < vCount.length) {
  94974. if (vId[ofs] === vv.id)
  94975. break;
  94976. ++ofs;
  94977. }
  94978. if (ofs === vCount.length) {
  94979. vCount.push(1);
  94980. vId.push(vv.id);
  94981. }
  94982. else {
  94983. vCount[ofs]++;
  94984. }
  94985. }
  94986. }
  94987. for (j = 0; j < vCount.length; ++j) {
  94988. if (vCount[j] === 1) {
  94989. this.vertices[vId[j]].isBorder = true;
  94990. }
  94991. else {
  94992. this.vertices[vId[j]].isBorder = false;
  94993. }
  94994. }
  94995. }
  94996. };
  94997. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94998. if (identifyBorders === void 0) { identifyBorders = false; }
  94999. var i;
  95000. if (!identifyBorders) {
  95001. var newTrianglesVector = [];
  95002. for (i = 0; i < this.triangles.length; ++i) {
  95003. if (!this.triangles[i].deleted) {
  95004. newTrianglesVector.push(this.triangles[i]);
  95005. }
  95006. }
  95007. this.triangles = newTrianglesVector;
  95008. }
  95009. for (i = 0; i < this.vertices.length; ++i) {
  95010. this.vertices[i].triangleCount = 0;
  95011. this.vertices[i].triangleStart = 0;
  95012. }
  95013. var t;
  95014. var j;
  95015. var v;
  95016. for (i = 0; i < this.triangles.length; ++i) {
  95017. t = this.triangles[i];
  95018. for (j = 0; j < 3; ++j) {
  95019. v = t.vertices[j];
  95020. v.triangleCount++;
  95021. }
  95022. }
  95023. var tStart = 0;
  95024. for (i = 0; i < this.vertices.length; ++i) {
  95025. this.vertices[i].triangleStart = tStart;
  95026. tStart += this.vertices[i].triangleCount;
  95027. this.vertices[i].triangleCount = 0;
  95028. }
  95029. var newReferences = new Array(this.triangles.length * 3);
  95030. for (i = 0; i < this.triangles.length; ++i) {
  95031. t = this.triangles[i];
  95032. for (j = 0; j < 3; ++j) {
  95033. v = t.vertices[j];
  95034. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95035. v.triangleCount++;
  95036. }
  95037. }
  95038. this.references = newReferences;
  95039. if (identifyBorders) {
  95040. this.identifyBorder();
  95041. }
  95042. };
  95043. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95044. var x = point.x;
  95045. var y = point.y;
  95046. var z = point.z;
  95047. 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
  95048. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95049. };
  95050. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95051. var q = vertex1.q.add(vertex2.q);
  95052. var border = vertex1.isBorder && vertex2.isBorder;
  95053. var error = 0;
  95054. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95055. if (qDet !== 0 && !border) {
  95056. if (!pointResult) {
  95057. pointResult = BABYLON.Vector3.Zero();
  95058. }
  95059. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95060. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95061. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95062. error = this.vertexError(q, pointResult);
  95063. }
  95064. else {
  95065. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95066. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95067. var error1 = this.vertexError(q, vertex1.position);
  95068. var error2 = this.vertexError(q, vertex2.position);
  95069. var error3 = this.vertexError(q, p3);
  95070. error = Math.min(error1, error2, error3);
  95071. if (error === error1) {
  95072. if (pointResult) {
  95073. pointResult.copyFrom(vertex1.position);
  95074. }
  95075. }
  95076. else if (error === error2) {
  95077. if (pointResult) {
  95078. pointResult.copyFrom(vertex2.position);
  95079. }
  95080. }
  95081. else {
  95082. if (pointResult) {
  95083. pointResult.copyFrom(p3);
  95084. }
  95085. }
  95086. }
  95087. return error;
  95088. };
  95089. return QuadraticErrorSimplification;
  95090. }());
  95091. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95092. })(BABYLON || (BABYLON = {}));
  95093. //# sourceMappingURL=babylon.meshSimplification.js.map
  95094. var BABYLON;
  95095. (function (BABYLON) {
  95096. var MeshLODLevel = /** @class */ (function () {
  95097. function MeshLODLevel(distance, mesh) {
  95098. this.distance = distance;
  95099. this.mesh = mesh;
  95100. }
  95101. return MeshLODLevel;
  95102. }());
  95103. BABYLON.MeshLODLevel = MeshLODLevel;
  95104. })(BABYLON || (BABYLON = {}));
  95105. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95106. var BABYLON;
  95107. (function (BABYLON) {
  95108. /**
  95109. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95111. */
  95112. var SceneOptimization = /** @class */ (function () {
  95113. /**
  95114. * Creates the SceneOptimization object
  95115. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95116. * @param desc defines the description associated with the optimization
  95117. */
  95118. function SceneOptimization(
  95119. /**
  95120. * Defines the priority of this optimization (0 by default which means first in the list)
  95121. */
  95122. priority) {
  95123. if (priority === void 0) { priority = 0; }
  95124. this.priority = priority;
  95125. }
  95126. /**
  95127. * Gets a string describing the action executed by the current optimization
  95128. * @returns description string
  95129. */
  95130. SceneOptimization.prototype.getDescription = function () {
  95131. return "";
  95132. };
  95133. /**
  95134. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95135. * @param scene defines the current scene where to apply this optimization
  95136. * @param optimizer defines the current optimizer
  95137. * @returns true if everything that can be done was applied
  95138. */
  95139. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95140. return true;
  95141. };
  95142. ;
  95143. return SceneOptimization;
  95144. }());
  95145. BABYLON.SceneOptimization = SceneOptimization;
  95146. /**
  95147. * Defines an optimization used to reduce the size of render target textures
  95148. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95149. */
  95150. var TextureOptimization = /** @class */ (function (_super) {
  95151. __extends(TextureOptimization, _super);
  95152. /**
  95153. * Creates the TextureOptimization object
  95154. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95155. * @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
  95156. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95157. */
  95158. function TextureOptimization(
  95159. /**
  95160. * Defines the priority of this optimization (0 by default which means first in the list)
  95161. */
  95162. priority,
  95163. /**
  95164. * 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
  95165. */
  95166. maximumSize,
  95167. /**
  95168. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95169. */
  95170. step) {
  95171. if (priority === void 0) { priority = 0; }
  95172. if (maximumSize === void 0) { maximumSize = 1024; }
  95173. if (step === void 0) { step = 0.5; }
  95174. var _this = _super.call(this, priority) || this;
  95175. _this.priority = priority;
  95176. _this.maximumSize = maximumSize;
  95177. _this.step = step;
  95178. return _this;
  95179. }
  95180. /**
  95181. * Gets a string describing the action executed by the current optimization
  95182. * @returns description string
  95183. */
  95184. TextureOptimization.prototype.getDescription = function () {
  95185. return "Reducing render target texture size to " + this.maximumSize;
  95186. };
  95187. /**
  95188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95189. * @param scene defines the current scene where to apply this optimization
  95190. * @param optimizer defines the current optimizer
  95191. * @returns true if everything that can be done was applied
  95192. */
  95193. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95194. var allDone = true;
  95195. for (var index = 0; index < scene.textures.length; index++) {
  95196. var texture = scene.textures[index];
  95197. if (!texture.canRescale || texture.getContext) {
  95198. continue;
  95199. }
  95200. var currentSize = texture.getSize();
  95201. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95202. if (maxDimension > this.maximumSize) {
  95203. texture.scale(this.step);
  95204. allDone = false;
  95205. }
  95206. }
  95207. return allDone;
  95208. };
  95209. return TextureOptimization;
  95210. }(SceneOptimization));
  95211. BABYLON.TextureOptimization = TextureOptimization;
  95212. /**
  95213. * Defines an optimization used to increase or decrease the rendering resolution
  95214. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95215. */
  95216. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95217. __extends(HardwareScalingOptimization, _super);
  95218. /**
  95219. * Creates the HardwareScalingOptimization object
  95220. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95221. * @param maximumScale defines the maximum scale to use (2 by default)
  95222. * @param step defines the step to use between two passes (0.5 by default)
  95223. */
  95224. function HardwareScalingOptimization(
  95225. /**
  95226. * Defines the priority of this optimization (0 by default which means first in the list)
  95227. */
  95228. priority,
  95229. /**
  95230. * Defines the maximum scale to use (2 by default)
  95231. */
  95232. maximumScale,
  95233. /**
  95234. * Defines the step to use between two passes (0.5 by default)
  95235. */
  95236. step) {
  95237. if (priority === void 0) { priority = 0; }
  95238. if (maximumScale === void 0) { maximumScale = 2; }
  95239. if (step === void 0) { step = 0.25; }
  95240. var _this = _super.call(this, priority) || this;
  95241. _this.priority = priority;
  95242. _this.maximumScale = maximumScale;
  95243. _this.step = step;
  95244. _this._currentScale = -1;
  95245. _this._directionOffset = 1;
  95246. return _this;
  95247. }
  95248. /**
  95249. * Gets a string describing the action executed by the current optimization
  95250. * @return description string
  95251. */
  95252. HardwareScalingOptimization.prototype.getDescription = function () {
  95253. return "Setting hardware scaling level to " + this._currentScale;
  95254. };
  95255. /**
  95256. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95257. * @param scene defines the current scene where to apply this optimization
  95258. * @param optimizer defines the current optimizer
  95259. * @returns true if everything that can be done was applied
  95260. */
  95261. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95262. if (this._currentScale === -1) {
  95263. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95264. if (this._currentScale > this.maximumScale) {
  95265. this._directionOffset = -1;
  95266. }
  95267. }
  95268. this._currentScale += this._directionOffset * this.step;
  95269. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95270. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95271. };
  95272. ;
  95273. return HardwareScalingOptimization;
  95274. }(SceneOptimization));
  95275. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95276. /**
  95277. * Defines an optimization used to remove shadows
  95278. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95279. */
  95280. var ShadowsOptimization = /** @class */ (function (_super) {
  95281. __extends(ShadowsOptimization, _super);
  95282. function ShadowsOptimization() {
  95283. return _super !== null && _super.apply(this, arguments) || this;
  95284. }
  95285. /**
  95286. * Gets a string describing the action executed by the current optimization
  95287. * @return description string
  95288. */
  95289. ShadowsOptimization.prototype.getDescription = function () {
  95290. return "Turning shadows on/off";
  95291. };
  95292. /**
  95293. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95294. * @param scene defines the current scene where to apply this optimization
  95295. * @param optimizer defines the current optimizer
  95296. * @returns true if everything that can be done was applied
  95297. */
  95298. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95299. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95300. return true;
  95301. };
  95302. ;
  95303. return ShadowsOptimization;
  95304. }(SceneOptimization));
  95305. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95306. /**
  95307. * Defines an optimization used to turn post-processes off
  95308. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95309. */
  95310. var PostProcessesOptimization = /** @class */ (function (_super) {
  95311. __extends(PostProcessesOptimization, _super);
  95312. function PostProcessesOptimization() {
  95313. return _super !== null && _super.apply(this, arguments) || this;
  95314. }
  95315. /**
  95316. * Gets a string describing the action executed by the current optimization
  95317. * @return description string
  95318. */
  95319. PostProcessesOptimization.prototype.getDescription = function () {
  95320. return "Turning post-processes on/off";
  95321. };
  95322. /**
  95323. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95324. * @param scene defines the current scene where to apply this optimization
  95325. * @param optimizer defines the current optimizer
  95326. * @returns true if everything that can be done was applied
  95327. */
  95328. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95329. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95330. return true;
  95331. };
  95332. ;
  95333. return PostProcessesOptimization;
  95334. }(SceneOptimization));
  95335. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95336. /**
  95337. * Defines an optimization used to turn lens flares off
  95338. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95339. */
  95340. var LensFlaresOptimization = /** @class */ (function (_super) {
  95341. __extends(LensFlaresOptimization, _super);
  95342. function LensFlaresOptimization() {
  95343. return _super !== null && _super.apply(this, arguments) || this;
  95344. }
  95345. /**
  95346. * Gets a string describing the action executed by the current optimization
  95347. * @return description string
  95348. */
  95349. LensFlaresOptimization.prototype.getDescription = function () {
  95350. return "Turning lens flares on/off";
  95351. };
  95352. /**
  95353. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95354. * @param scene defines the current scene where to apply this optimization
  95355. * @param optimizer defines the current optimizer
  95356. * @returns true if everything that can be done was applied
  95357. */
  95358. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95359. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95360. return true;
  95361. };
  95362. ;
  95363. return LensFlaresOptimization;
  95364. }(SceneOptimization));
  95365. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95366. /**
  95367. * Defines an optimization based on user defined callback.
  95368. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95369. */
  95370. var CustomOptimization = /** @class */ (function (_super) {
  95371. __extends(CustomOptimization, _super);
  95372. function CustomOptimization() {
  95373. return _super !== null && _super.apply(this, arguments) || this;
  95374. }
  95375. /**
  95376. * Gets a string describing the action executed by the current optimization
  95377. * @returns description string
  95378. */
  95379. CustomOptimization.prototype.getDescription = function () {
  95380. if (this.onGetDescription) {
  95381. return this.onGetDescription();
  95382. }
  95383. return "Running user defined callback";
  95384. };
  95385. /**
  95386. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95387. * @param scene defines the current scene where to apply this optimization
  95388. * @param optimizer defines the current optimizer
  95389. * @returns true if everything that can be done was applied
  95390. */
  95391. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95392. if (this.onApply) {
  95393. return this.onApply(scene, optimizer);
  95394. }
  95395. return true;
  95396. };
  95397. ;
  95398. return CustomOptimization;
  95399. }(SceneOptimization));
  95400. BABYLON.CustomOptimization = CustomOptimization;
  95401. /**
  95402. * Defines an optimization used to turn particles off
  95403. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95404. */
  95405. var ParticlesOptimization = /** @class */ (function (_super) {
  95406. __extends(ParticlesOptimization, _super);
  95407. function ParticlesOptimization() {
  95408. return _super !== null && _super.apply(this, arguments) || this;
  95409. }
  95410. /**
  95411. * Gets a string describing the action executed by the current optimization
  95412. * @return description string
  95413. */
  95414. ParticlesOptimization.prototype.getDescription = function () {
  95415. return "Turning particles on/off";
  95416. };
  95417. /**
  95418. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95419. * @param scene defines the current scene where to apply this optimization
  95420. * @param optimizer defines the current optimizer
  95421. * @returns true if everything that can be done was applied
  95422. */
  95423. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95424. scene.particlesEnabled = optimizer.isInImprovementMode;
  95425. return true;
  95426. };
  95427. ;
  95428. return ParticlesOptimization;
  95429. }(SceneOptimization));
  95430. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95431. /**
  95432. * Defines an optimization used to turn render targets off
  95433. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95434. */
  95435. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95436. __extends(RenderTargetsOptimization, _super);
  95437. function RenderTargetsOptimization() {
  95438. return _super !== null && _super.apply(this, arguments) || this;
  95439. }
  95440. /**
  95441. * Gets a string describing the action executed by the current optimization
  95442. * @return description string
  95443. */
  95444. RenderTargetsOptimization.prototype.getDescription = function () {
  95445. return "Turning render targets off";
  95446. };
  95447. /**
  95448. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95449. * @param scene defines the current scene where to apply this optimization
  95450. * @param optimizer defines the current optimizer
  95451. * @returns true if everything that can be done was applied
  95452. */
  95453. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95454. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95455. return true;
  95456. };
  95457. ;
  95458. return RenderTargetsOptimization;
  95459. }(SceneOptimization));
  95460. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95461. /**
  95462. * Defines an optimization used to merge meshes with compatible materials
  95463. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95464. */
  95465. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95466. __extends(MergeMeshesOptimization, _super);
  95467. function MergeMeshesOptimization() {
  95468. var _this = _super !== null && _super.apply(this, arguments) || this;
  95469. _this._canBeMerged = function (abstractMesh) {
  95470. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95471. return false;
  95472. }
  95473. var mesh = abstractMesh;
  95474. if (mesh.isDisposed()) {
  95475. return false;
  95476. }
  95477. if (!mesh.isVisible || !mesh.isEnabled()) {
  95478. return false;
  95479. }
  95480. if (mesh.instances.length > 0) {
  95481. return false;
  95482. }
  95483. if (mesh.skeleton || mesh.hasLODLevels) {
  95484. return false;
  95485. }
  95486. return true;
  95487. };
  95488. return _this;
  95489. }
  95490. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95491. /**
  95492. * Gets or sets a boolean which defines if optimization octree has to be updated
  95493. */
  95494. get: function () {
  95495. return MergeMeshesOptimization._UpdateSelectionTree;
  95496. },
  95497. /**
  95498. * Gets or sets a boolean which defines if optimization octree has to be updated
  95499. */
  95500. set: function (value) {
  95501. MergeMeshesOptimization._UpdateSelectionTree = value;
  95502. },
  95503. enumerable: true,
  95504. configurable: true
  95505. });
  95506. /**
  95507. * Gets a string describing the action executed by the current optimization
  95508. * @return description string
  95509. */
  95510. MergeMeshesOptimization.prototype.getDescription = function () {
  95511. return "Merging similar meshes together";
  95512. };
  95513. /**
  95514. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95515. * @param scene defines the current scene where to apply this optimization
  95516. * @param optimizer defines the current optimizer
  95517. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95518. * @returns true if everything that can be done was applied
  95519. */
  95520. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95521. var globalPool = scene.meshes.slice(0);
  95522. var globalLength = globalPool.length;
  95523. for (var index = 0; index < globalLength; index++) {
  95524. var currentPool = new Array();
  95525. var current = globalPool[index];
  95526. // Checks
  95527. if (!this._canBeMerged(current)) {
  95528. continue;
  95529. }
  95530. currentPool.push(current);
  95531. // Find compatible meshes
  95532. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95533. var otherMesh = globalPool[subIndex];
  95534. if (!this._canBeMerged(otherMesh)) {
  95535. continue;
  95536. }
  95537. if (otherMesh.material !== current.material) {
  95538. continue;
  95539. }
  95540. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95541. continue;
  95542. }
  95543. currentPool.push(otherMesh);
  95544. globalLength--;
  95545. globalPool.splice(subIndex, 1);
  95546. subIndex--;
  95547. }
  95548. if (currentPool.length < 2) {
  95549. continue;
  95550. }
  95551. // Merge meshes
  95552. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95553. }
  95554. if (updateSelectionTree != undefined) {
  95555. if (updateSelectionTree) {
  95556. scene.createOrUpdateSelectionOctree();
  95557. }
  95558. }
  95559. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95560. scene.createOrUpdateSelectionOctree();
  95561. }
  95562. return true;
  95563. };
  95564. ;
  95565. MergeMeshesOptimization._UpdateSelectionTree = false;
  95566. return MergeMeshesOptimization;
  95567. }(SceneOptimization));
  95568. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95569. /**
  95570. * Defines a list of options used by SceneOptimizer
  95571. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95572. */
  95573. var SceneOptimizerOptions = /** @class */ (function () {
  95574. /**
  95575. * Creates a new list of options used by SceneOptimizer
  95576. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95577. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95578. */
  95579. function SceneOptimizerOptions(
  95580. /**
  95581. * Defines the target frame rate to reach (60 by default)
  95582. */
  95583. targetFrameRate,
  95584. /**
  95585. * Defines the interval between two checkes (2000ms by default)
  95586. */
  95587. trackerDuration) {
  95588. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95589. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95590. this.targetFrameRate = targetFrameRate;
  95591. this.trackerDuration = trackerDuration;
  95592. /**
  95593. * Gets the list of optimizations to apply
  95594. */
  95595. this.optimizations = new Array();
  95596. }
  95597. /**
  95598. * Add a new optimization
  95599. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95600. * @returns the current SceneOptimizerOptions
  95601. */
  95602. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95603. this.optimizations.push(optimization);
  95604. return this;
  95605. };
  95606. /**
  95607. * Add a new custom optimization
  95608. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95609. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95610. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95611. * @returns the current SceneOptimizerOptions
  95612. */
  95613. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95614. if (priority === void 0) { priority = 0; }
  95615. var optimization = new CustomOptimization(priority);
  95616. optimization.onApply = onApply;
  95617. optimization.onGetDescription = onGetDescription;
  95618. this.optimizations.push(optimization);
  95619. return this;
  95620. };
  95621. /**
  95622. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95623. * @param targetFrameRate defines the target frame rate (60 by default)
  95624. * @returns a SceneOptimizerOptions object
  95625. */
  95626. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95627. var result = new SceneOptimizerOptions(targetFrameRate);
  95628. var priority = 0;
  95629. result.addOptimization(new MergeMeshesOptimization(priority));
  95630. result.addOptimization(new ShadowsOptimization(priority));
  95631. result.addOptimization(new LensFlaresOptimization(priority));
  95632. // Next priority
  95633. priority++;
  95634. result.addOptimization(new PostProcessesOptimization(priority));
  95635. result.addOptimization(new ParticlesOptimization(priority));
  95636. // Next priority
  95637. priority++;
  95638. result.addOptimization(new TextureOptimization(priority, 1024));
  95639. return result;
  95640. };
  95641. /**
  95642. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95643. * @param targetFrameRate defines the target frame rate (60 by default)
  95644. * @returns a SceneOptimizerOptions object
  95645. */
  95646. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95647. var result = new SceneOptimizerOptions(targetFrameRate);
  95648. var priority = 0;
  95649. result.addOptimization(new MergeMeshesOptimization(priority));
  95650. result.addOptimization(new ShadowsOptimization(priority));
  95651. result.addOptimization(new LensFlaresOptimization(priority));
  95652. // Next priority
  95653. priority++;
  95654. result.addOptimization(new PostProcessesOptimization(priority));
  95655. result.addOptimization(new ParticlesOptimization(priority));
  95656. // Next priority
  95657. priority++;
  95658. result.addOptimization(new TextureOptimization(priority, 512));
  95659. // Next priority
  95660. priority++;
  95661. result.addOptimization(new RenderTargetsOptimization(priority));
  95662. // Next priority
  95663. priority++;
  95664. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95665. return result;
  95666. };
  95667. /**
  95668. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95669. * @param targetFrameRate defines the target frame rate (60 by default)
  95670. * @returns a SceneOptimizerOptions object
  95671. */
  95672. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95673. var result = new SceneOptimizerOptions(targetFrameRate);
  95674. var priority = 0;
  95675. result.addOptimization(new MergeMeshesOptimization(priority));
  95676. result.addOptimization(new ShadowsOptimization(priority));
  95677. result.addOptimization(new LensFlaresOptimization(priority));
  95678. // Next priority
  95679. priority++;
  95680. result.addOptimization(new PostProcessesOptimization(priority));
  95681. result.addOptimization(new ParticlesOptimization(priority));
  95682. // Next priority
  95683. priority++;
  95684. result.addOptimization(new TextureOptimization(priority, 256));
  95685. // Next priority
  95686. priority++;
  95687. result.addOptimization(new RenderTargetsOptimization(priority));
  95688. // Next priority
  95689. priority++;
  95690. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95691. return result;
  95692. };
  95693. return SceneOptimizerOptions;
  95694. }());
  95695. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95696. /**
  95697. * Class used to run optimizations in order to reach a target frame rate
  95698. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95699. */
  95700. var SceneOptimizer = /** @class */ (function () {
  95701. /**
  95702. * Creates a new SceneOptimizer
  95703. * @param scene defines the scene to work on
  95704. * @param options defines the options to use with the SceneOptimizer
  95705. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95706. * @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)
  95707. */
  95708. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95709. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95710. if (improvementMode === void 0) { improvementMode = false; }
  95711. var _this = this;
  95712. this._isRunning = false;
  95713. this._currentPriorityLevel = 0;
  95714. this._targetFrameRate = 60;
  95715. this._trackerDuration = 2000;
  95716. this._currentFrameRate = 0;
  95717. this._improvementMode = false;
  95718. /**
  95719. * Defines an observable called when the optimizer reaches the target frame rate
  95720. */
  95721. this.onSuccessObservable = new BABYLON.Observable();
  95722. /**
  95723. * Defines an observable called when the optimizer enables an optimization
  95724. */
  95725. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95726. /**
  95727. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95728. */
  95729. this.onFailureObservable = new BABYLON.Observable();
  95730. if (!options) {
  95731. this._options = new SceneOptimizerOptions();
  95732. }
  95733. else {
  95734. this._options = options;
  95735. }
  95736. if (this._options.targetFrameRate) {
  95737. this._targetFrameRate = this._options.targetFrameRate;
  95738. }
  95739. if (this._options.trackerDuration) {
  95740. this._trackerDuration = this._options.trackerDuration;
  95741. }
  95742. if (autoGeneratePriorities) {
  95743. var priority = 0;
  95744. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95745. var optim = _a[_i];
  95746. optim.priority = priority++;
  95747. }
  95748. }
  95749. this._improvementMode = improvementMode;
  95750. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95751. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95752. _this._sceneDisposeObserver = null;
  95753. _this.dispose();
  95754. });
  95755. }
  95756. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95757. /**
  95758. * Gets a boolean indicating if the optimizer is in improvement mode
  95759. */
  95760. get: function () {
  95761. return this._improvementMode;
  95762. },
  95763. enumerable: true,
  95764. configurable: true
  95765. });
  95766. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95767. /**
  95768. * Gets the current priority level (0 at start)
  95769. */
  95770. get: function () {
  95771. return this._currentPriorityLevel;
  95772. },
  95773. enumerable: true,
  95774. configurable: true
  95775. });
  95776. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95777. /**
  95778. * Gets the current frame rate checked by the SceneOptimizer
  95779. */
  95780. get: function () {
  95781. return this._currentFrameRate;
  95782. },
  95783. enumerable: true,
  95784. configurable: true
  95785. });
  95786. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95787. /**
  95788. * Gets or sets the current target frame rate (60 by default)
  95789. */
  95790. get: function () {
  95791. return this._targetFrameRate;
  95792. },
  95793. /**
  95794. * Gets or sets the current target frame rate (60 by default)
  95795. */
  95796. set: function (value) {
  95797. this._targetFrameRate = value;
  95798. },
  95799. enumerable: true,
  95800. configurable: true
  95801. });
  95802. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95803. /**
  95804. * Gets or sets the current interval between two checks (every 2000ms by default)
  95805. */
  95806. get: function () {
  95807. return this._trackerDuration;
  95808. },
  95809. /**
  95810. * Gets or sets the current interval between two checks (every 2000ms by default)
  95811. */
  95812. set: function (value) {
  95813. this._trackerDuration = value;
  95814. },
  95815. enumerable: true,
  95816. configurable: true
  95817. });
  95818. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95819. /**
  95820. * Gets the list of active optimizations
  95821. */
  95822. get: function () {
  95823. return this._options.optimizations;
  95824. },
  95825. enumerable: true,
  95826. configurable: true
  95827. });
  95828. /**
  95829. * Stops the current optimizer
  95830. */
  95831. SceneOptimizer.prototype.stop = function () {
  95832. this._isRunning = false;
  95833. };
  95834. /**
  95835. * Reset the optimizer to initial step (current priority level = 0)
  95836. */
  95837. SceneOptimizer.prototype.reset = function () {
  95838. this._currentPriorityLevel = 0;
  95839. };
  95840. /**
  95841. * Start the optimizer. By default it will try to reach a specific framerate
  95842. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95843. */
  95844. SceneOptimizer.prototype.start = function () {
  95845. var _this = this;
  95846. if (this._isRunning) {
  95847. return;
  95848. }
  95849. this._isRunning = true;
  95850. // Let's wait for the scene to be ready before running our check
  95851. this._scene.executeWhenReady(function () {
  95852. setTimeout(function () {
  95853. _this._checkCurrentState();
  95854. }, _this._trackerDuration);
  95855. });
  95856. };
  95857. SceneOptimizer.prototype._checkCurrentState = function () {
  95858. var _this = this;
  95859. if (!this._isRunning) {
  95860. return;
  95861. }
  95862. var scene = this._scene;
  95863. var options = this._options;
  95864. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95865. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95866. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95867. this._isRunning = false;
  95868. this.onSuccessObservable.notifyObservers(this);
  95869. return;
  95870. }
  95871. // Apply current level of optimizations
  95872. var allDone = true;
  95873. var noOptimizationApplied = true;
  95874. for (var index = 0; index < options.optimizations.length; index++) {
  95875. var optimization = options.optimizations[index];
  95876. if (optimization.priority === this._currentPriorityLevel) {
  95877. noOptimizationApplied = false;
  95878. allDone = allDone && optimization.apply(scene, this);
  95879. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95880. }
  95881. }
  95882. // If no optimization was applied, this is a failure :(
  95883. if (noOptimizationApplied) {
  95884. this._isRunning = false;
  95885. this.onFailureObservable.notifyObservers(this);
  95886. return;
  95887. }
  95888. // If all optimizations were done, move to next level
  95889. if (allDone) {
  95890. this._currentPriorityLevel++;
  95891. }
  95892. // Let's the system running for a specific amount of time before checking FPS
  95893. scene.executeWhenReady(function () {
  95894. setTimeout(function () {
  95895. _this._checkCurrentState();
  95896. }, _this._trackerDuration);
  95897. });
  95898. };
  95899. /**
  95900. * Release all resources
  95901. */
  95902. SceneOptimizer.prototype.dispose = function () {
  95903. this.stop();
  95904. this.onSuccessObservable.clear();
  95905. this.onFailureObservable.clear();
  95906. this.onNewOptimizationAppliedObservable.clear();
  95907. if (this._sceneDisposeObserver) {
  95908. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95909. }
  95910. };
  95911. /**
  95912. * Helper function to create a SceneOptimizer with one single line of code
  95913. * @param scene defines the scene to work on
  95914. * @param options defines the options to use with the SceneOptimizer
  95915. * @param onSuccess defines a callback to call on success
  95916. * @param onFailure defines a callback to call on failure
  95917. * @returns the new SceneOptimizer object
  95918. */
  95919. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95920. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95921. if (onSuccess) {
  95922. optimizer.onSuccessObservable.add(function () {
  95923. onSuccess();
  95924. });
  95925. }
  95926. if (onFailure) {
  95927. optimizer.onFailureObservable.add(function () {
  95928. onFailure();
  95929. });
  95930. }
  95931. optimizer.start();
  95932. return optimizer;
  95933. };
  95934. return SceneOptimizer;
  95935. }());
  95936. BABYLON.SceneOptimizer = SceneOptimizer;
  95937. })(BABYLON || (BABYLON = {}));
  95938. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95939. var BABYLON;
  95940. (function (BABYLON) {
  95941. var OutlineRenderer = /** @class */ (function () {
  95942. function OutlineRenderer(scene) {
  95943. this.zOffset = 1;
  95944. this._scene = scene;
  95945. }
  95946. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95947. var _this = this;
  95948. if (useOverlay === void 0) { useOverlay = false; }
  95949. var scene = this._scene;
  95950. var engine = this._scene.getEngine();
  95951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95952. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95953. return;
  95954. }
  95955. var mesh = subMesh.getRenderingMesh();
  95956. var material = subMesh.getMaterial();
  95957. if (!material || !scene.activeCamera) {
  95958. return;
  95959. }
  95960. engine.enableEffect(this._effect);
  95961. // Logarithmic depth
  95962. if (material.useLogarithmicDepth) {
  95963. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95964. }
  95965. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95966. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95967. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95968. // Bones
  95969. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95970. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95971. }
  95972. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95973. // Alpha test
  95974. if (material && material.needAlphaTesting()) {
  95975. var alphaTexture = material.getAlphaTestTexture();
  95976. if (alphaTexture) {
  95977. this._effect.setTexture("diffuseSampler", alphaTexture);
  95978. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95979. }
  95980. }
  95981. engine.setZOffset(-this.zOffset);
  95982. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95983. engine.setZOffset(0);
  95984. };
  95985. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95986. var defines = [];
  95987. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95988. var mesh = subMesh.getMesh();
  95989. var material = subMesh.getMaterial();
  95990. if (material) {
  95991. // Alpha test
  95992. if (material.needAlphaTesting()) {
  95993. defines.push("#define ALPHATEST");
  95994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95995. attribs.push(BABYLON.VertexBuffer.UVKind);
  95996. defines.push("#define UV1");
  95997. }
  95998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96000. defines.push("#define UV2");
  96001. }
  96002. }
  96003. //Logarithmic depth
  96004. if (material.useLogarithmicDepth) {
  96005. defines.push("#define LOGARITHMICDEPTH");
  96006. }
  96007. }
  96008. // Bones
  96009. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96010. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96011. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96012. if (mesh.numBoneInfluencers > 4) {
  96013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96015. }
  96016. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96017. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96018. }
  96019. else {
  96020. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96021. }
  96022. // Instances
  96023. if (useInstances) {
  96024. defines.push("#define INSTANCES");
  96025. attribs.push("world0");
  96026. attribs.push("world1");
  96027. attribs.push("world2");
  96028. attribs.push("world3");
  96029. }
  96030. // Get correct effect
  96031. var join = defines.join("\n");
  96032. if (this._cachedDefines !== join) {
  96033. this._cachedDefines = join;
  96034. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96035. }
  96036. return this._effect.isReady();
  96037. };
  96038. return OutlineRenderer;
  96039. }());
  96040. BABYLON.OutlineRenderer = OutlineRenderer;
  96041. })(BABYLON || (BABYLON = {}));
  96042. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96043. var BABYLON;
  96044. (function (BABYLON) {
  96045. var FaceAdjacencies = /** @class */ (function () {
  96046. function FaceAdjacencies() {
  96047. this.edges = new Array();
  96048. this.edgesConnectedCount = 0;
  96049. }
  96050. return FaceAdjacencies;
  96051. }());
  96052. var EdgesRenderer = /** @class */ (function () {
  96053. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96054. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96055. if (epsilon === void 0) { epsilon = 0.95; }
  96056. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96057. this.edgesWidthScalerForOrthographic = 1000.0;
  96058. this.edgesWidthScalerForPerspective = 50.0;
  96059. this._linesPositions = new Array();
  96060. this._linesNormals = new Array();
  96061. this._linesIndices = new Array();
  96062. this._buffers = {};
  96063. this._checkVerticesInsteadOfIndices = false;
  96064. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96065. this.isEnabled = true;
  96066. this._source = source;
  96067. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96068. this._epsilon = epsilon;
  96069. this._prepareRessources();
  96070. this._generateEdgesLines();
  96071. }
  96072. EdgesRenderer.prototype._prepareRessources = function () {
  96073. if (this._lineShader) {
  96074. return;
  96075. }
  96076. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96077. attributes: ["position", "normal"],
  96078. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96079. });
  96080. this._lineShader.disableDepthWrite = true;
  96081. this._lineShader.backFaceCulling = false;
  96082. };
  96083. EdgesRenderer.prototype._rebuild = function () {
  96084. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96085. if (buffer) {
  96086. buffer._rebuild();
  96087. }
  96088. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96089. if (buffer) {
  96090. buffer._rebuild();
  96091. }
  96092. var scene = this._source.getScene();
  96093. var engine = scene.getEngine();
  96094. this._ib = engine.createIndexBuffer(this._linesIndices);
  96095. };
  96096. EdgesRenderer.prototype.dispose = function () {
  96097. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96098. if (buffer) {
  96099. buffer.dispose();
  96100. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96101. }
  96102. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96103. if (buffer) {
  96104. buffer.dispose();
  96105. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96106. }
  96107. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96108. this._lineShader.dispose();
  96109. };
  96110. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96111. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96112. return 0;
  96113. }
  96114. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96115. return 1;
  96116. }
  96117. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96118. return 2;
  96119. }
  96120. return -1;
  96121. };
  96122. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96123. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96124. return 0;
  96125. }
  96126. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96127. return 1;
  96128. }
  96129. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96130. return 2;
  96131. }
  96132. return -1;
  96133. };
  96134. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96135. var needToCreateLine;
  96136. if (edge === undefined) {
  96137. needToCreateLine = true;
  96138. }
  96139. else {
  96140. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96141. needToCreateLine = dotProduct < this._epsilon;
  96142. }
  96143. if (needToCreateLine) {
  96144. var offset = this._linesPositions.length / 3;
  96145. var normal = p0.subtract(p1);
  96146. normal.normalize();
  96147. // Positions
  96148. this._linesPositions.push(p0.x);
  96149. this._linesPositions.push(p0.y);
  96150. this._linesPositions.push(p0.z);
  96151. this._linesPositions.push(p0.x);
  96152. this._linesPositions.push(p0.y);
  96153. this._linesPositions.push(p0.z);
  96154. this._linesPositions.push(p1.x);
  96155. this._linesPositions.push(p1.y);
  96156. this._linesPositions.push(p1.z);
  96157. this._linesPositions.push(p1.x);
  96158. this._linesPositions.push(p1.y);
  96159. this._linesPositions.push(p1.z);
  96160. // Normals
  96161. this._linesNormals.push(p1.x);
  96162. this._linesNormals.push(p1.y);
  96163. this._linesNormals.push(p1.z);
  96164. this._linesNormals.push(-1);
  96165. this._linesNormals.push(p1.x);
  96166. this._linesNormals.push(p1.y);
  96167. this._linesNormals.push(p1.z);
  96168. this._linesNormals.push(1);
  96169. this._linesNormals.push(p0.x);
  96170. this._linesNormals.push(p0.y);
  96171. this._linesNormals.push(p0.z);
  96172. this._linesNormals.push(-1);
  96173. this._linesNormals.push(p0.x);
  96174. this._linesNormals.push(p0.y);
  96175. this._linesNormals.push(p0.z);
  96176. this._linesNormals.push(1);
  96177. // Indices
  96178. this._linesIndices.push(offset);
  96179. this._linesIndices.push(offset + 1);
  96180. this._linesIndices.push(offset + 2);
  96181. this._linesIndices.push(offset);
  96182. this._linesIndices.push(offset + 2);
  96183. this._linesIndices.push(offset + 3);
  96184. }
  96185. };
  96186. EdgesRenderer.prototype._generateEdgesLines = function () {
  96187. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96188. var indices = this._source.getIndices();
  96189. if (!indices || !positions) {
  96190. return;
  96191. }
  96192. // First let's find adjacencies
  96193. var adjacencies = new Array();
  96194. var faceNormals = new Array();
  96195. var index;
  96196. var faceAdjacencies;
  96197. // Prepare faces
  96198. for (index = 0; index < indices.length; index += 3) {
  96199. faceAdjacencies = new FaceAdjacencies();
  96200. var p0Index = indices[index];
  96201. var p1Index = indices[index + 1];
  96202. var p2Index = indices[index + 2];
  96203. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96204. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96205. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96206. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96207. faceNormal.normalize();
  96208. faceNormals.push(faceNormal);
  96209. adjacencies.push(faceAdjacencies);
  96210. }
  96211. // Scan
  96212. for (index = 0; index < adjacencies.length; index++) {
  96213. faceAdjacencies = adjacencies[index];
  96214. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96215. var otherFaceAdjacencies = adjacencies[otherIndex];
  96216. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96217. break;
  96218. }
  96219. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96220. continue;
  96221. }
  96222. var otherP0 = indices[otherIndex * 3];
  96223. var otherP1 = indices[otherIndex * 3 + 1];
  96224. var otherP2 = indices[otherIndex * 3 + 2];
  96225. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96226. var otherEdgeIndex = 0;
  96227. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96228. continue;
  96229. }
  96230. switch (edgeIndex) {
  96231. case 0:
  96232. if (this._checkVerticesInsteadOfIndices) {
  96233. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96234. }
  96235. else {
  96236. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96237. }
  96238. break;
  96239. case 1:
  96240. if (this._checkVerticesInsteadOfIndices) {
  96241. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96242. }
  96243. else {
  96244. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96245. }
  96246. break;
  96247. case 2:
  96248. if (this._checkVerticesInsteadOfIndices) {
  96249. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96250. }
  96251. else {
  96252. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96253. }
  96254. break;
  96255. }
  96256. if (otherEdgeIndex === -1) {
  96257. continue;
  96258. }
  96259. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96260. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96261. faceAdjacencies.edgesConnectedCount++;
  96262. otherFaceAdjacencies.edgesConnectedCount++;
  96263. if (faceAdjacencies.edgesConnectedCount === 3) {
  96264. break;
  96265. }
  96266. }
  96267. }
  96268. }
  96269. // Create lines
  96270. for (index = 0; index < adjacencies.length; index++) {
  96271. // 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
  96272. var current = adjacencies[index];
  96273. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96274. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96275. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96276. }
  96277. // Merge into a single mesh
  96278. var engine = this._source.getScene().getEngine();
  96279. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96280. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96281. this._ib = engine.createIndexBuffer(this._linesIndices);
  96282. this._indicesCount = this._linesIndices.length;
  96283. };
  96284. EdgesRenderer.prototype.render = function () {
  96285. var scene = this._source.getScene();
  96286. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96287. return;
  96288. }
  96289. var engine = scene.getEngine();
  96290. this._lineShader._preBind();
  96291. // VBOs
  96292. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96293. scene.resetCachedMaterial();
  96294. this._lineShader.setColor4("color", this._source.edgesColor);
  96295. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96296. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96297. }
  96298. else {
  96299. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96300. }
  96301. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96302. this._lineShader.bind(this._source.getWorldMatrix());
  96303. // Draw order
  96304. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96305. this._lineShader.unbind();
  96306. engine.setDepthWrite(true);
  96307. };
  96308. return EdgesRenderer;
  96309. }());
  96310. BABYLON.EdgesRenderer = EdgesRenderer;
  96311. })(BABYLON || (BABYLON = {}));
  96312. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96313. var BABYLON;
  96314. (function (BABYLON) {
  96315. // Adds the parser to the scene parsers.
  96316. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96317. if (parsedData.effectLayers) {
  96318. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96319. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96320. container.effectLayers.push(effectLayer);
  96321. }
  96322. }
  96323. });
  96324. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96325. var index = this.effectLayers.indexOf(toRemove);
  96326. if (index !== -1) {
  96327. this.effectLayers.splice(index, 1);
  96328. }
  96329. return index;
  96330. };
  96331. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96332. this.effectLayers.push(newEffectLayer);
  96333. };
  96334. /**
  96335. * Defines the layer scene component responsible to manage any effect layers
  96336. * in a given scene.
  96337. */
  96338. var EffectLayerSceneComponent = /** @class */ (function () {
  96339. /**
  96340. * Creates a new instance of the component for the given scene
  96341. * @param scene Defines the scene to register the component in
  96342. */
  96343. function EffectLayerSceneComponent(scene) {
  96344. /**
  96345. * The component name helpfull to identify the component in the list of scene components.
  96346. */
  96347. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96348. this._renderEffects = false;
  96349. this._needStencil = false;
  96350. this._previousStencilState = false;
  96351. this.scene = scene;
  96352. this._engine = scene.getEngine();
  96353. scene.effectLayers = new Array();
  96354. }
  96355. /**
  96356. * Registers the component in a given scene
  96357. */
  96358. EffectLayerSceneComponent.prototype.register = function () {
  96359. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96360. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96361. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96362. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96363. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96364. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96365. };
  96366. /**
  96367. * Rebuilds the elements related to this component in case of
  96368. * context lost for instance.
  96369. */
  96370. EffectLayerSceneComponent.prototype.rebuild = function () {
  96371. var layers = this.scene.effectLayers;
  96372. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96373. var effectLayer = layers_1[_i];
  96374. effectLayer._rebuild();
  96375. }
  96376. };
  96377. /**
  96378. * Serializes the component data to the specified json object
  96379. * @param serializationObject The object to serialize to
  96380. */
  96381. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96382. // Effect layers
  96383. serializationObject.effectLayers = [];
  96384. var layers = this.scene.effectLayers;
  96385. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96386. var effectLayer = layers_2[_i];
  96387. if (effectLayer.serialize) {
  96388. serializationObject.effectLayers.push(effectLayer.serialize());
  96389. }
  96390. }
  96391. };
  96392. /**
  96393. * Adds all the element from the container to the scene
  96394. * @param container the container holding the elements
  96395. */
  96396. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96397. var _this = this;
  96398. if (!container.effectLayers) {
  96399. return;
  96400. }
  96401. container.effectLayers.forEach(function (o) {
  96402. _this.scene.addEffectLayer(o);
  96403. });
  96404. };
  96405. /**
  96406. * Removes all the elements in the container from the scene
  96407. * @param container contains the elements to remove
  96408. */
  96409. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96410. var _this = this;
  96411. if (!container.effectLayers) {
  96412. return;
  96413. }
  96414. container.effectLayers.forEach(function (o) {
  96415. _this.scene.removeEffectLayer(o);
  96416. });
  96417. };
  96418. /**
  96419. * Disposes the component and the associated ressources.
  96420. */
  96421. EffectLayerSceneComponent.prototype.dispose = function () {
  96422. var layers = this.scene.effectLayers;
  96423. while (layers.length) {
  96424. layers[0].dispose();
  96425. }
  96426. };
  96427. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96428. var layers = this.scene.effectLayers;
  96429. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96430. var layer = layers_3[_i];
  96431. if (!layer.hasMesh(mesh)) {
  96432. continue;
  96433. }
  96434. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96435. var subMesh = _b[_a];
  96436. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96437. return false;
  96438. }
  96439. }
  96440. }
  96441. return true;
  96442. };
  96443. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96444. this._renderEffects = false;
  96445. this._needStencil = false;
  96446. var layers = this.scene.effectLayers;
  96447. if (layers && layers.length > 0) {
  96448. this._previousStencilState = this._engine.getStencilBuffer();
  96449. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96450. var effectLayer = layers_4[_i];
  96451. if (effectLayer.shouldRender() &&
  96452. (!effectLayer.camera ||
  96453. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96454. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96455. this._renderEffects = true;
  96456. this._needStencil = this._needStencil || effectLayer.needStencil();
  96457. var renderTarget = effectLayer._mainTexture;
  96458. if (renderTarget._shouldRender()) {
  96459. this.scene.incrementRenderId();
  96460. renderTarget.render(false, false);
  96461. }
  96462. }
  96463. }
  96464. this.scene.incrementRenderId();
  96465. }
  96466. };
  96467. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96468. // Activate effect Layer stencil
  96469. if (this._needStencil) {
  96470. this._engine.setStencilBuffer(true);
  96471. }
  96472. };
  96473. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96474. // Restore effect Layer stencil
  96475. if (this._needStencil) {
  96476. this._engine.setStencilBuffer(this._previousStencilState);
  96477. }
  96478. };
  96479. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96480. if (this._renderEffects) {
  96481. this._engine.setDepthBuffer(false);
  96482. var layers = this.scene.effectLayers;
  96483. for (var i = 0; i < layers.length; i++) {
  96484. var effectLayer = layers[i];
  96485. if (effectLayer.renderingGroupId === renderingGroupId) {
  96486. if (effectLayer.shouldRender()) {
  96487. effectLayer.render();
  96488. }
  96489. }
  96490. }
  96491. this._engine.setDepthBuffer(true);
  96492. }
  96493. };
  96494. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96495. if (this._renderEffects) {
  96496. this._draw(-1);
  96497. }
  96498. };
  96499. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96500. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96501. this._draw(index);
  96502. }
  96503. };
  96504. return EffectLayerSceneComponent;
  96505. }());
  96506. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96507. })(BABYLON || (BABYLON = {}));
  96508. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96509. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96510. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96511. s = arguments[i];
  96512. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96513. t[p] = s[p];
  96514. }
  96515. return t;
  96516. };
  96517. var BABYLON;
  96518. (function (BABYLON) {
  96519. /**
  96520. * The effect layer Helps adding post process effect blended with the main pass.
  96521. *
  96522. * This can be for instance use to generate glow or higlight effects on the scene.
  96523. *
  96524. * The effect layer class can not be used directly and is intented to inherited from to be
  96525. * customized per effects.
  96526. */
  96527. var EffectLayer = /** @class */ (function () {
  96528. /**
  96529. * Instantiates a new effect Layer and references it in the scene.
  96530. * @param name The name of the layer
  96531. * @param scene The scene to use the layer in
  96532. */
  96533. function EffectLayer(
  96534. /** The Friendly of the effect in the scene */
  96535. name, scene) {
  96536. this._vertexBuffers = {};
  96537. this._maxSize = 0;
  96538. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96539. this._shouldRender = true;
  96540. this._postProcesses = [];
  96541. this._textures = [];
  96542. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96543. /**
  96544. * The clear color of the texture used to generate the glow map.
  96545. */
  96546. this.neutralColor = new BABYLON.Color4();
  96547. /**
  96548. * Specifies wether the highlight layer is enabled or not.
  96549. */
  96550. this.isEnabled = true;
  96551. /**
  96552. * An event triggered when the effect layer has been disposed.
  96553. */
  96554. this.onDisposeObservable = new BABYLON.Observable();
  96555. /**
  96556. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96557. */
  96558. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96559. /**
  96560. * An event triggered when the generated texture is being merged in the scene.
  96561. */
  96562. this.onBeforeComposeObservable = new BABYLON.Observable();
  96563. /**
  96564. * An event triggered when the generated texture has been merged in the scene.
  96565. */
  96566. this.onAfterComposeObservable = new BABYLON.Observable();
  96567. /**
  96568. * An event triggered when the efffect layer changes its size.
  96569. */
  96570. this.onSizeChangedObservable = new BABYLON.Observable();
  96571. this.name = name;
  96572. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96573. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96574. if (!component) {
  96575. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96576. this._scene._addComponent(component);
  96577. }
  96578. this._engine = this._scene.getEngine();
  96579. this._maxSize = this._engine.getCaps().maxTextureSize;
  96580. this._scene.effectLayers.push(this);
  96581. // Generate Buffers
  96582. this._generateIndexBuffer();
  96583. this._genrateVertexBuffer();
  96584. }
  96585. Object.defineProperty(EffectLayer.prototype, "camera", {
  96586. /**
  96587. * Gets the camera attached to the layer.
  96588. */
  96589. get: function () {
  96590. return this._effectLayerOptions.camera;
  96591. },
  96592. enumerable: true,
  96593. configurable: true
  96594. });
  96595. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96596. /**
  96597. * Gets the rendering group id the layer should render in.
  96598. */
  96599. get: function () {
  96600. return this._effectLayerOptions.renderingGroupId;
  96601. },
  96602. enumerable: true,
  96603. configurable: true
  96604. });
  96605. /**
  96606. * Initializes the effect layer with the required options.
  96607. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96608. */
  96609. EffectLayer.prototype._init = function (options) {
  96610. // Adapt options
  96611. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96612. this._setMainTextureSize();
  96613. this._createMainTexture();
  96614. this._createTextureAndPostProcesses();
  96615. this._mergeEffect = this._createMergeEffect();
  96616. };
  96617. /**
  96618. * Generates the index buffer of the full screen quad blending to the main canvas.
  96619. */
  96620. EffectLayer.prototype._generateIndexBuffer = function () {
  96621. // Indices
  96622. var indices = [];
  96623. indices.push(0);
  96624. indices.push(1);
  96625. indices.push(2);
  96626. indices.push(0);
  96627. indices.push(2);
  96628. indices.push(3);
  96629. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96630. };
  96631. /**
  96632. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96633. */
  96634. EffectLayer.prototype._genrateVertexBuffer = function () {
  96635. // VBO
  96636. var vertices = [];
  96637. vertices.push(1, 1);
  96638. vertices.push(-1, 1);
  96639. vertices.push(-1, -1);
  96640. vertices.push(1, -1);
  96641. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96642. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96643. };
  96644. /**
  96645. * Sets the main texture desired size which is the closest power of two
  96646. * of the engine canvas size.
  96647. */
  96648. EffectLayer.prototype._setMainTextureSize = function () {
  96649. if (this._effectLayerOptions.mainTextureFixedSize) {
  96650. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96651. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96652. }
  96653. else {
  96654. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96655. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96656. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96657. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96658. }
  96659. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96660. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96661. };
  96662. /**
  96663. * Creates the main texture for the effect layer.
  96664. */
  96665. EffectLayer.prototype._createMainTexture = function () {
  96666. var _this = this;
  96667. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96668. width: this._mainTextureDesiredSize.width,
  96669. height: this._mainTextureDesiredSize.height
  96670. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96671. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96672. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96673. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96674. this._mainTexture.anisotropicFilteringLevel = 1;
  96675. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96676. this._mainTexture.renderParticles = false;
  96677. this._mainTexture.renderList = null;
  96678. this._mainTexture.ignoreCameraViewport = true;
  96679. // Custom render function
  96680. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96681. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96682. var index;
  96683. var engine = _this._scene.getEngine();
  96684. if (depthOnlySubMeshes.length) {
  96685. engine.setColorWrite(false);
  96686. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96687. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96688. }
  96689. engine.setColorWrite(true);
  96690. }
  96691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96692. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96693. }
  96694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96695. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96696. }
  96697. for (index = 0; index < transparentSubMeshes.length; index++) {
  96698. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96699. }
  96700. };
  96701. this._mainTexture.onClearObservable.add(function (engine) {
  96702. engine.clear(_this.neutralColor, true, true, true);
  96703. });
  96704. };
  96705. /**
  96706. * Checks for the readiness of the element composing the layer.
  96707. * @param subMesh the mesh to check for
  96708. * @param useInstances specify wether or not to use instances to render the mesh
  96709. * @param emissiveTexture the associated emissive texture used to generate the glow
  96710. * @return true if ready otherwise, false
  96711. */
  96712. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96713. var material = subMesh.getMaterial();
  96714. if (!material) {
  96715. return false;
  96716. }
  96717. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96718. return false;
  96719. }
  96720. var defines = [];
  96721. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96722. var mesh = subMesh.getMesh();
  96723. var uv1 = false;
  96724. var uv2 = false;
  96725. // Alpha test
  96726. if (material && material.needAlphaTesting()) {
  96727. var alphaTexture = material.getAlphaTestTexture();
  96728. if (alphaTexture) {
  96729. defines.push("#define ALPHATEST");
  96730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96731. alphaTexture.coordinatesIndex === 1) {
  96732. defines.push("#define DIFFUSEUV2");
  96733. uv2 = true;
  96734. }
  96735. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96736. defines.push("#define DIFFUSEUV1");
  96737. uv1 = true;
  96738. }
  96739. }
  96740. }
  96741. // Emissive
  96742. if (emissiveTexture) {
  96743. defines.push("#define EMISSIVE");
  96744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96745. emissiveTexture.coordinatesIndex === 1) {
  96746. defines.push("#define EMISSIVEUV2");
  96747. uv2 = true;
  96748. }
  96749. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96750. defines.push("#define EMISSIVEUV1");
  96751. uv1 = true;
  96752. }
  96753. }
  96754. if (uv1) {
  96755. attribs.push(BABYLON.VertexBuffer.UVKind);
  96756. defines.push("#define UV1");
  96757. }
  96758. if (uv2) {
  96759. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96760. defines.push("#define UV2");
  96761. }
  96762. // Bones
  96763. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96766. if (mesh.numBoneInfluencers > 4) {
  96767. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96768. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96769. }
  96770. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96771. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96772. }
  96773. else {
  96774. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96775. }
  96776. // Morph targets
  96777. var manager = mesh.morphTargetManager;
  96778. var morphInfluencers = 0;
  96779. if (manager) {
  96780. if (manager.numInfluencers > 0) {
  96781. defines.push("#define MORPHTARGETS");
  96782. morphInfluencers = manager.numInfluencers;
  96783. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96784. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96785. }
  96786. }
  96787. // Instances
  96788. if (useInstances) {
  96789. defines.push("#define INSTANCES");
  96790. attribs.push("world0");
  96791. attribs.push("world1");
  96792. attribs.push("world2");
  96793. attribs.push("world3");
  96794. }
  96795. // Get correct effect
  96796. var join = defines.join("\n");
  96797. if (this._cachedDefines !== join) {
  96798. this._cachedDefines = join;
  96799. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96800. }
  96801. return this._effectLayerMapGenerationEffect.isReady();
  96802. };
  96803. /**
  96804. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96805. */
  96806. EffectLayer.prototype.render = function () {
  96807. var currentEffect = this._mergeEffect;
  96808. // Check
  96809. if (!currentEffect.isReady())
  96810. return;
  96811. for (var i = 0; i < this._postProcesses.length; i++) {
  96812. if (!this._postProcesses[i].isReady()) {
  96813. return;
  96814. }
  96815. }
  96816. var engine = this._scene.getEngine();
  96817. this.onBeforeComposeObservable.notifyObservers(this);
  96818. // Render
  96819. engine.enableEffect(currentEffect);
  96820. engine.setState(false);
  96821. // VBOs
  96822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96823. // Cache
  96824. var previousAlphaMode = engine.getAlphaMode();
  96825. // Go Blend.
  96826. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96827. // Blends the map on the main canvas.
  96828. this._internalRender(currentEffect);
  96829. // Restore Alpha
  96830. engine.setAlphaMode(previousAlphaMode);
  96831. this.onAfterComposeObservable.notifyObservers(this);
  96832. // Handle size changes.
  96833. var size = this._mainTexture.getSize();
  96834. this._setMainTextureSize();
  96835. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96836. // Recreate RTT and post processes on size change.
  96837. this.onSizeChangedObservable.notifyObservers(this);
  96838. this._disposeTextureAndPostProcesses();
  96839. this._createMainTexture();
  96840. this._createTextureAndPostProcesses();
  96841. }
  96842. };
  96843. /**
  96844. * Determine if a given mesh will be used in the current effect.
  96845. * @param mesh mesh to test
  96846. * @returns true if the mesh will be used
  96847. */
  96848. EffectLayer.prototype.hasMesh = function (mesh) {
  96849. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96850. return true;
  96851. }
  96852. return false;
  96853. };
  96854. /**
  96855. * Returns true if the layer contains information to display, otherwise false.
  96856. * @returns true if the glow layer should be rendered
  96857. */
  96858. EffectLayer.prototype.shouldRender = function () {
  96859. return this.isEnabled && this._shouldRender;
  96860. };
  96861. /**
  96862. * Returns true if the mesh should render, otherwise false.
  96863. * @param mesh The mesh to render
  96864. * @returns true if it should render otherwise false
  96865. */
  96866. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96867. return true;
  96868. };
  96869. /**
  96870. * Returns true if the mesh should render, otherwise false.
  96871. * @param mesh The mesh to render
  96872. * @returns true if it should render otherwise false
  96873. */
  96874. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96875. return true;
  96876. };
  96877. /**
  96878. * Renders the submesh passed in parameter to the generation map.
  96879. */
  96880. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96881. var _this = this;
  96882. if (!this.shouldRender()) {
  96883. return;
  96884. }
  96885. var material = subMesh.getMaterial();
  96886. var mesh = subMesh.getRenderingMesh();
  96887. var scene = this._scene;
  96888. var engine = scene.getEngine();
  96889. if (!material) {
  96890. return;
  96891. }
  96892. // Do not block in blend mode.
  96893. if (material.needAlphaBlendingForMesh(mesh)) {
  96894. return;
  96895. }
  96896. // Culling
  96897. engine.setState(material.backFaceCulling);
  96898. // Managing instances
  96899. var batch = mesh._getInstancesRenderList(subMesh._id);
  96900. if (batch.mustReturn) {
  96901. return;
  96902. }
  96903. // Early Exit per mesh
  96904. if (!this._shouldRenderMesh(mesh)) {
  96905. return;
  96906. }
  96907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96908. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96909. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96910. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96911. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96912. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96913. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96914. // Alpha test
  96915. if (material && material.needAlphaTesting()) {
  96916. var alphaTexture = material.getAlphaTestTexture();
  96917. if (alphaTexture) {
  96918. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96919. var textureMatrix = alphaTexture.getTextureMatrix();
  96920. if (textureMatrix) {
  96921. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96922. }
  96923. }
  96924. }
  96925. // Glow emissive only
  96926. if (this._emissiveTextureAndColor.texture) {
  96927. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96928. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96929. }
  96930. // Bones
  96931. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96932. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96933. }
  96934. // Morph targets
  96935. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96936. // Draw
  96937. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96938. }
  96939. else {
  96940. // Need to reset refresh rate of the main map
  96941. this._mainTexture.resetRefreshCounter();
  96942. }
  96943. };
  96944. /**
  96945. * Rebuild the required buffers.
  96946. * @hidden Internal use only.
  96947. */
  96948. EffectLayer.prototype._rebuild = function () {
  96949. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96950. if (vb) {
  96951. vb._rebuild();
  96952. }
  96953. this._generateIndexBuffer();
  96954. };
  96955. /**
  96956. * Dispose only the render target textures and post process.
  96957. */
  96958. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96959. this._mainTexture.dispose();
  96960. for (var i = 0; i < this._postProcesses.length; i++) {
  96961. if (this._postProcesses[i]) {
  96962. this._postProcesses[i].dispose();
  96963. }
  96964. }
  96965. this._postProcesses = [];
  96966. for (var i = 0; i < this._textures.length; i++) {
  96967. if (this._textures[i]) {
  96968. this._textures[i].dispose();
  96969. }
  96970. }
  96971. this._textures = [];
  96972. };
  96973. /**
  96974. * Dispose the highlight layer and free resources.
  96975. */
  96976. EffectLayer.prototype.dispose = function () {
  96977. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96978. if (vertexBuffer) {
  96979. vertexBuffer.dispose();
  96980. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96981. }
  96982. if (this._indexBuffer) {
  96983. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96984. this._indexBuffer = null;
  96985. }
  96986. // Clean textures and post processes
  96987. this._disposeTextureAndPostProcesses();
  96988. // Remove from scene
  96989. var index = this._scene.effectLayers.indexOf(this, 0);
  96990. if (index > -1) {
  96991. this._scene.effectLayers.splice(index, 1);
  96992. }
  96993. // Callback
  96994. this.onDisposeObservable.notifyObservers(this);
  96995. this.onDisposeObservable.clear();
  96996. this.onBeforeRenderMainTextureObservable.clear();
  96997. this.onBeforeComposeObservable.clear();
  96998. this.onAfterComposeObservable.clear();
  96999. this.onSizeChangedObservable.clear();
  97000. };
  97001. /**
  97002. * Gets the class name of the effect layer
  97003. * @returns the string with the class name of the effect layer
  97004. */
  97005. EffectLayer.prototype.getClassName = function () {
  97006. return "EffectLayer";
  97007. };
  97008. /**
  97009. * Creates an effect layer from parsed effect layer data
  97010. * @param parsedEffectLayer defines effect layer data
  97011. * @param scene defines the current scene
  97012. * @param rootUrl defines the root URL containing the effect layer information
  97013. * @returns a parsed effect Layer
  97014. */
  97015. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97016. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97017. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97018. };
  97019. __decorate([
  97020. BABYLON.serialize()
  97021. ], EffectLayer.prototype, "name", void 0);
  97022. __decorate([
  97023. BABYLON.serializeAsColor4()
  97024. ], EffectLayer.prototype, "neutralColor", void 0);
  97025. __decorate([
  97026. BABYLON.serialize()
  97027. ], EffectLayer.prototype, "isEnabled", void 0);
  97028. __decorate([
  97029. BABYLON.serializeAsCameraReference()
  97030. ], EffectLayer.prototype, "camera", null);
  97031. __decorate([
  97032. BABYLON.serialize()
  97033. ], EffectLayer.prototype, "renderingGroupId", null);
  97034. return EffectLayer;
  97035. }());
  97036. BABYLON.EffectLayer = EffectLayer;
  97037. })(BABYLON || (BABYLON = {}));
  97038. //# sourceMappingURL=babylon.effectLayer.js.map
  97039. var BABYLON;
  97040. (function (BABYLON) {
  97041. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97042. for (var index = 0; index < this.effectLayers.length; index++) {
  97043. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97044. return this.effectLayers[index];
  97045. }
  97046. }
  97047. return null;
  97048. };
  97049. /**
  97050. * Special Glow Blur post process only blurring the alpha channel
  97051. * It enforces keeping the most luminous color in the color channel.
  97052. */
  97053. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97054. __extends(GlowBlurPostProcess, _super);
  97055. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97057. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97058. _this.direction = direction;
  97059. _this.kernel = kernel;
  97060. _this.onApplyObservable.add(function (effect) {
  97061. effect.setFloat2("screenSize", _this.width, _this.height);
  97062. effect.setVector2("direction", _this.direction);
  97063. effect.setFloat("blurWidth", _this.kernel);
  97064. });
  97065. return _this;
  97066. }
  97067. return GlowBlurPostProcess;
  97068. }(BABYLON.PostProcess));
  97069. /**
  97070. * The highlight layer Helps adding a glow effect around a mesh.
  97071. *
  97072. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97073. * glowy meshes to your scene.
  97074. *
  97075. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97076. */
  97077. var HighlightLayer = /** @class */ (function (_super) {
  97078. __extends(HighlightLayer, _super);
  97079. /**
  97080. * Instantiates a new highlight Layer and references it to the scene..
  97081. * @param name The name of the layer
  97082. * @param scene The scene to use the layer in
  97083. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97084. */
  97085. function HighlightLayer(name, scene, options) {
  97086. var _this = _super.call(this, name, scene) || this;
  97087. _this.name = name;
  97088. /**
  97089. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97090. */
  97091. _this.innerGlow = true;
  97092. /**
  97093. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97094. */
  97095. _this.outerGlow = true;
  97096. /**
  97097. * An event triggered when the highlight layer is being blurred.
  97098. */
  97099. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97100. /**
  97101. * An event triggered when the highlight layer has been blurred.
  97102. */
  97103. _this.onAfterBlurObservable = new BABYLON.Observable();
  97104. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97105. _this._meshes = {};
  97106. _this._excludedMeshes = {};
  97107. _this.neutralColor = HighlightLayer.NeutralColor;
  97108. // Warn on stencil
  97109. if (!_this._engine.isStencilEnable) {
  97110. 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 }");
  97111. }
  97112. // Adapt options
  97113. _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);
  97114. // Initialize the layer
  97115. _this._init({
  97116. alphaBlendingMode: _this._options.alphaBlendingMode,
  97117. camera: _this._options.camera,
  97118. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97119. mainTextureRatio: _this._options.mainTextureRatio,
  97120. renderingGroupId: _this._options.renderingGroupId
  97121. });
  97122. // Do not render as long as no meshes have been added
  97123. _this._shouldRender = false;
  97124. return _this;
  97125. }
  97126. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97127. /**
  97128. * Gets the horizontal size of the blur.
  97129. */
  97130. get: function () {
  97131. return this._horizontalBlurPostprocess.kernel;
  97132. },
  97133. /**
  97134. * Specifies the horizontal size of the blur.
  97135. */
  97136. set: function (value) {
  97137. this._horizontalBlurPostprocess.kernel = value;
  97138. },
  97139. enumerable: true,
  97140. configurable: true
  97141. });
  97142. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97143. /**
  97144. * Gets the vertical size of the blur.
  97145. */
  97146. get: function () {
  97147. return this._verticalBlurPostprocess.kernel;
  97148. },
  97149. /**
  97150. * Specifies the vertical size of the blur.
  97151. */
  97152. set: function (value) {
  97153. this._verticalBlurPostprocess.kernel = value;
  97154. },
  97155. enumerable: true,
  97156. configurable: true
  97157. });
  97158. /**
  97159. * Get the effect name of the layer.
  97160. * @return The effect name
  97161. */
  97162. HighlightLayer.prototype.getEffectName = function () {
  97163. return HighlightLayer.EffectName;
  97164. };
  97165. /**
  97166. * Create the merge effect. This is the shader use to blit the information back
  97167. * to the main canvas at the end of the scene rendering.
  97168. */
  97169. HighlightLayer.prototype._createMergeEffect = function () {
  97170. // Effect
  97171. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97172. };
  97173. /**
  97174. * Creates the render target textures and post processes used in the highlight layer.
  97175. */
  97176. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97177. var _this = this;
  97178. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97179. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97180. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97181. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97182. var textureType = 0;
  97183. if (this._engine.getCaps().textureHalfFloatRender) {
  97184. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97185. }
  97186. else {
  97187. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97188. }
  97189. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97190. width: blurTextureWidth,
  97191. height: blurTextureHeight
  97192. }, this._scene, false, true, textureType);
  97193. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97194. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97195. this._blurTexture.anisotropicFilteringLevel = 16;
  97196. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97197. this._blurTexture.renderParticles = false;
  97198. this._blurTexture.ignoreCameraViewport = true;
  97199. this._textures = [this._blurTexture];
  97200. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97201. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97202. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97203. effect.setTexture("textureSampler", _this._mainTexture);
  97204. });
  97205. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97206. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97207. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97208. });
  97209. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97210. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97211. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97212. });
  97213. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97214. }
  97215. else {
  97216. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97217. width: blurTextureWidth,
  97218. height: blurTextureHeight
  97219. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97220. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97221. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97222. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97223. effect.setTexture("textureSampler", _this._mainTexture);
  97224. });
  97225. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97226. width: blurTextureWidth,
  97227. height: blurTextureHeight
  97228. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97229. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97230. }
  97231. this._mainTexture.onAfterUnbindObservable.add(function () {
  97232. _this.onBeforeBlurObservable.notifyObservers(_this);
  97233. var internalTexture = _this._blurTexture.getInternalTexture();
  97234. if (internalTexture) {
  97235. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97236. }
  97237. _this.onAfterBlurObservable.notifyObservers(_this);
  97238. });
  97239. // Prevent autoClear.
  97240. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97241. };
  97242. /**
  97243. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97244. */
  97245. HighlightLayer.prototype.needStencil = function () {
  97246. return true;
  97247. };
  97248. /**
  97249. * Checks for the readiness of the element composing the layer.
  97250. * @param subMesh the mesh to check for
  97251. * @param useInstances specify wether or not to use instances to render the mesh
  97252. * @param emissiveTexture the associated emissive texture used to generate the glow
  97253. * @return true if ready otherwise, false
  97254. */
  97255. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97256. var material = subMesh.getMaterial();
  97257. var mesh = subMesh.getRenderingMesh();
  97258. if (!material || !mesh || !this._meshes) {
  97259. return false;
  97260. }
  97261. var emissiveTexture = null;
  97262. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97263. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97264. emissiveTexture = material.emissiveTexture;
  97265. }
  97266. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97267. };
  97268. /**
  97269. * Implementation specific of rendering the generating effect on the main canvas.
  97270. * @param effect The effect used to render through
  97271. */
  97272. HighlightLayer.prototype._internalRender = function (effect) {
  97273. // Texture
  97274. effect.setTexture("textureSampler", this._blurTexture);
  97275. // Cache
  97276. var engine = this._engine;
  97277. var previousStencilBuffer = engine.getStencilBuffer();
  97278. var previousStencilFunction = engine.getStencilFunction();
  97279. var previousStencilMask = engine.getStencilMask();
  97280. var previousStencilOperationPass = engine.getStencilOperationPass();
  97281. var previousStencilOperationFail = engine.getStencilOperationFail();
  97282. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97283. var previousStencilReference = engine.getStencilFunctionReference();
  97284. // Stencil operations
  97285. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97286. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97287. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97288. // Draw order
  97289. engine.setStencilMask(0x00);
  97290. engine.setStencilBuffer(true);
  97291. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97292. // 2 passes inner outer
  97293. if (this.outerGlow) {
  97294. effect.setFloat("offset", 0);
  97295. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97296. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97297. }
  97298. if (this.innerGlow) {
  97299. effect.setFloat("offset", 1);
  97300. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97301. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97302. }
  97303. // Restore Cache
  97304. engine.setStencilFunction(previousStencilFunction);
  97305. engine.setStencilMask(previousStencilMask);
  97306. engine.setStencilBuffer(previousStencilBuffer);
  97307. engine.setStencilOperationPass(previousStencilOperationPass);
  97308. engine.setStencilOperationFail(previousStencilOperationFail);
  97309. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97310. engine.setStencilFunctionReference(previousStencilReference);
  97311. };
  97312. /**
  97313. * Returns true if the layer contains information to display, otherwise false.
  97314. */
  97315. HighlightLayer.prototype.shouldRender = function () {
  97316. if (_super.prototype.shouldRender.call(this)) {
  97317. return this._meshes ? true : false;
  97318. }
  97319. return false;
  97320. };
  97321. /**
  97322. * Returns true if the mesh should render, otherwise false.
  97323. * @param mesh The mesh to render
  97324. * @returns true if it should render otherwise false
  97325. */
  97326. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97327. // Excluded Mesh
  97328. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97329. return false;
  97330. }
  97331. ;
  97332. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97333. return false;
  97334. }
  97335. return true;
  97336. };
  97337. /**
  97338. * Sets the required values for both the emissive texture and and the main color.
  97339. */
  97340. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97341. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97342. if (highlightLayerMesh) {
  97343. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97344. }
  97345. else {
  97346. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97347. }
  97348. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97349. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97350. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97351. }
  97352. else {
  97353. this._emissiveTextureAndColor.texture = null;
  97354. }
  97355. };
  97356. /**
  97357. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97358. * @param mesh The mesh to exclude from the highlight layer
  97359. */
  97360. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97361. if (!this._excludedMeshes) {
  97362. return;
  97363. }
  97364. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97365. if (!meshExcluded) {
  97366. this._excludedMeshes[mesh.uniqueId] = {
  97367. mesh: mesh,
  97368. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97369. mesh.getEngine().setStencilBuffer(false);
  97370. }),
  97371. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97372. mesh.getEngine().setStencilBuffer(true);
  97373. }),
  97374. };
  97375. }
  97376. };
  97377. /**
  97378. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97379. * @param mesh The mesh to highlight
  97380. */
  97381. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97382. if (!this._excludedMeshes) {
  97383. return;
  97384. }
  97385. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97386. if (meshExcluded) {
  97387. if (meshExcluded.beforeRender) {
  97388. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97389. }
  97390. if (meshExcluded.afterRender) {
  97391. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97392. }
  97393. }
  97394. this._excludedMeshes[mesh.uniqueId] = null;
  97395. };
  97396. /**
  97397. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97398. * @param mesh mesh to test
  97399. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97400. */
  97401. HighlightLayer.prototype.hasMesh = function (mesh) {
  97402. if (!this._meshes) {
  97403. return false;
  97404. }
  97405. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97406. return false;
  97407. }
  97408. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97409. };
  97410. /**
  97411. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97412. * @param mesh The mesh to highlight
  97413. * @param color The color of the highlight
  97414. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97415. */
  97416. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97417. var _this = this;
  97418. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97419. if (!this._meshes) {
  97420. return;
  97421. }
  97422. var meshHighlight = this._meshes[mesh.uniqueId];
  97423. if (meshHighlight) {
  97424. meshHighlight.color = color;
  97425. }
  97426. else {
  97427. this._meshes[mesh.uniqueId] = {
  97428. mesh: mesh,
  97429. color: color,
  97430. // Lambda required for capture due to Observable this context
  97431. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97432. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97433. _this._defaultStencilReference(mesh);
  97434. }
  97435. else {
  97436. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97437. }
  97438. }),
  97439. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97440. glowEmissiveOnly: glowEmissiveOnly
  97441. };
  97442. mesh.onDisposeObservable.add(function () {
  97443. _this._disposeMesh(mesh);
  97444. });
  97445. }
  97446. this._shouldRender = true;
  97447. };
  97448. /**
  97449. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97450. * @param mesh The mesh to highlight
  97451. */
  97452. HighlightLayer.prototype.removeMesh = function (mesh) {
  97453. if (!this._meshes) {
  97454. return;
  97455. }
  97456. var meshHighlight = this._meshes[mesh.uniqueId];
  97457. if (meshHighlight) {
  97458. if (meshHighlight.observerHighlight) {
  97459. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97460. }
  97461. if (meshHighlight.observerDefault) {
  97462. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97463. }
  97464. delete this._meshes[mesh.uniqueId];
  97465. }
  97466. this._shouldRender = false;
  97467. for (var meshHighlightToCheck in this._meshes) {
  97468. if (this._meshes[meshHighlightToCheck]) {
  97469. this._shouldRender = true;
  97470. break;
  97471. }
  97472. }
  97473. };
  97474. /**
  97475. * Force the stencil to the normal expected value for none glowing parts
  97476. */
  97477. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97478. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97479. };
  97480. /**
  97481. * Free any resources and references associated to a mesh.
  97482. * Internal use
  97483. * @param mesh The mesh to free.
  97484. */
  97485. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97486. this.removeMesh(mesh);
  97487. this.removeExcludedMesh(mesh);
  97488. };
  97489. /**
  97490. * Dispose the highlight layer and free resources.
  97491. */
  97492. HighlightLayer.prototype.dispose = function () {
  97493. if (this._meshes) {
  97494. // Clean mesh references
  97495. for (var id in this._meshes) {
  97496. var meshHighlight = this._meshes[id];
  97497. if (meshHighlight && meshHighlight.mesh) {
  97498. if (meshHighlight.observerHighlight) {
  97499. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97500. }
  97501. if (meshHighlight.observerDefault) {
  97502. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97503. }
  97504. }
  97505. }
  97506. this._meshes = null;
  97507. }
  97508. if (this._excludedMeshes) {
  97509. for (var id in this._excludedMeshes) {
  97510. var meshHighlight = this._excludedMeshes[id];
  97511. if (meshHighlight) {
  97512. if (meshHighlight.beforeRender) {
  97513. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97514. }
  97515. if (meshHighlight.afterRender) {
  97516. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97517. }
  97518. }
  97519. }
  97520. this._excludedMeshes = null;
  97521. }
  97522. _super.prototype.dispose.call(this);
  97523. };
  97524. /**
  97525. * Gets the class name of the effect layer
  97526. * @returns the string with the class name of the effect layer
  97527. */
  97528. HighlightLayer.prototype.getClassName = function () {
  97529. return "HighlightLayer";
  97530. };
  97531. /**
  97532. * Serializes this Highlight layer
  97533. * @returns a serialized Highlight layer object
  97534. */
  97535. HighlightLayer.prototype.serialize = function () {
  97536. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97537. serializationObject.customType = "BABYLON.HighlightLayer";
  97538. // Highlighted meshes
  97539. serializationObject.meshes = [];
  97540. if (this._meshes) {
  97541. for (var m in this._meshes) {
  97542. var mesh = this._meshes[m];
  97543. if (mesh) {
  97544. serializationObject.meshes.push({
  97545. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97546. color: mesh.color.asArray(),
  97547. meshId: mesh.mesh.id
  97548. });
  97549. }
  97550. }
  97551. }
  97552. // Excluded meshes
  97553. serializationObject.excludedMeshes = [];
  97554. if (this._excludedMeshes) {
  97555. for (var e in this._excludedMeshes) {
  97556. var excludedMesh = this._excludedMeshes[e];
  97557. if (excludedMesh) {
  97558. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97559. }
  97560. }
  97561. }
  97562. return serializationObject;
  97563. };
  97564. /**
  97565. * Creates a Highlight layer from parsed Highlight layer data
  97566. * @param parsedHightlightLayer defines the Highlight layer data
  97567. * @param scene defines the current scene
  97568. * @param rootUrl defines the root URL containing the Highlight layer information
  97569. * @returns a parsed Highlight layer
  97570. */
  97571. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97572. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97573. var index;
  97574. // Excluded meshes
  97575. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97576. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97577. if (mesh) {
  97578. hl.addExcludedMesh(mesh);
  97579. }
  97580. }
  97581. // Included meshes
  97582. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97583. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97584. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97585. if (mesh) {
  97586. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97587. }
  97588. }
  97589. return hl;
  97590. };
  97591. /**
  97592. * Effect Name of the highlight layer.
  97593. */
  97594. HighlightLayer.EffectName = "HighlightLayer";
  97595. /**
  97596. * The neutral color used during the preparation of the glow effect.
  97597. * This is black by default as the blend operation is a blend operation.
  97598. */
  97599. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97600. /**
  97601. * Stencil value used for glowing meshes.
  97602. */
  97603. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97604. /**
  97605. * Stencil value used for the other meshes in the scene.
  97606. */
  97607. HighlightLayer.NormalMeshStencilReference = 0x01;
  97608. __decorate([
  97609. BABYLON.serialize()
  97610. ], HighlightLayer.prototype, "innerGlow", void 0);
  97611. __decorate([
  97612. BABYLON.serialize()
  97613. ], HighlightLayer.prototype, "outerGlow", void 0);
  97614. __decorate([
  97615. BABYLON.serialize()
  97616. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97617. __decorate([
  97618. BABYLON.serialize()
  97619. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97620. __decorate([
  97621. BABYLON.serialize("options")
  97622. ], HighlightLayer.prototype, "_options", void 0);
  97623. return HighlightLayer;
  97624. }(BABYLON.EffectLayer));
  97625. BABYLON.HighlightLayer = HighlightLayer;
  97626. })(BABYLON || (BABYLON = {}));
  97627. //# sourceMappingURL=babylon.highlightLayer.js.map
  97628. var BABYLON;
  97629. (function (BABYLON) {
  97630. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97631. for (var index = 0; index < this.effectLayers.length; index++) {
  97632. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97633. return this.effectLayers[index];
  97634. }
  97635. }
  97636. return null;
  97637. };
  97638. /**
  97639. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97640. *
  97641. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97642. * glowy meshes to your scene.
  97643. *
  97644. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97645. */
  97646. var GlowLayer = /** @class */ (function (_super) {
  97647. __extends(GlowLayer, _super);
  97648. /**
  97649. * Instantiates a new glow Layer and references it to the scene.
  97650. * @param name The name of the layer
  97651. * @param scene The scene to use the layer in
  97652. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97653. */
  97654. function GlowLayer(name, scene, options) {
  97655. var _this = _super.call(this, name, scene) || this;
  97656. _this._intensity = 1.0;
  97657. _this._includedOnlyMeshes = [];
  97658. _this._excludedMeshes = [];
  97659. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97660. // Adapt options
  97661. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97662. // Initialize the layer
  97663. _this._init({
  97664. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97665. camera: _this._options.camera,
  97666. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97667. mainTextureRatio: _this._options.mainTextureRatio,
  97668. renderingGroupId: _this._options.renderingGroupId
  97669. });
  97670. return _this;
  97671. }
  97672. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97673. /**
  97674. * Gets the kernel size of the blur.
  97675. */
  97676. get: function () {
  97677. return this._horizontalBlurPostprocess1.kernel;
  97678. },
  97679. /**
  97680. * Sets the kernel size of the blur.
  97681. */
  97682. set: function (value) {
  97683. this._horizontalBlurPostprocess1.kernel = value;
  97684. this._verticalBlurPostprocess1.kernel = value;
  97685. this._horizontalBlurPostprocess2.kernel = value;
  97686. this._verticalBlurPostprocess2.kernel = value;
  97687. },
  97688. enumerable: true,
  97689. configurable: true
  97690. });
  97691. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97692. /**
  97693. * Gets the glow intensity.
  97694. */
  97695. get: function () {
  97696. return this._intensity;
  97697. },
  97698. /**
  97699. * Sets the glow intensity.
  97700. */
  97701. set: function (value) {
  97702. this._intensity = value;
  97703. },
  97704. enumerable: true,
  97705. configurable: true
  97706. });
  97707. /**
  97708. * Get the effect name of the layer.
  97709. * @return The effect name
  97710. */
  97711. GlowLayer.prototype.getEffectName = function () {
  97712. return GlowLayer.EffectName;
  97713. };
  97714. /**
  97715. * Create the merge effect. This is the shader use to blit the information back
  97716. * to the main canvas at the end of the scene rendering.
  97717. */
  97718. GlowLayer.prototype._createMergeEffect = function () {
  97719. // Effect
  97720. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97721. };
  97722. /**
  97723. * Creates the render target textures and post processes used in the glow layer.
  97724. */
  97725. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97726. var _this = this;
  97727. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97728. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97729. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97730. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97731. var textureType = 0;
  97732. if (this._engine.getCaps().textureHalfFloatRender) {
  97733. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97734. }
  97735. else {
  97736. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97737. }
  97738. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97739. width: blurTextureWidth,
  97740. height: blurTextureHeight
  97741. }, this._scene, false, true, textureType);
  97742. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97743. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97744. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97745. this._blurTexture1.renderParticles = false;
  97746. this._blurTexture1.ignoreCameraViewport = true;
  97747. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97748. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97749. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97750. width: blurTextureWidth2,
  97751. height: blurTextureHeight2
  97752. }, this._scene, false, true, textureType);
  97753. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97754. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97755. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97756. this._blurTexture2.renderParticles = false;
  97757. this._blurTexture2.ignoreCameraViewport = true;
  97758. this._textures = [this._blurTexture1, this._blurTexture2];
  97759. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97760. width: blurTextureWidth,
  97761. height: blurTextureHeight
  97762. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97763. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97764. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97765. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97766. effect.setTexture("textureSampler", _this._mainTexture);
  97767. });
  97768. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97769. width: blurTextureWidth,
  97770. height: blurTextureHeight
  97771. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97772. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97773. width: blurTextureWidth2,
  97774. height: blurTextureHeight2
  97775. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97776. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97777. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97778. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97779. effect.setTexture("textureSampler", _this._blurTexture1);
  97780. });
  97781. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97782. width: blurTextureWidth2,
  97783. height: blurTextureHeight2
  97784. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97785. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97786. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97787. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97788. this._mainTexture.samples = this._options.mainTextureSamples;
  97789. this._mainTexture.onAfterUnbindObservable.add(function () {
  97790. var internalTexture = _this._blurTexture1.getInternalTexture();
  97791. if (internalTexture) {
  97792. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97793. internalTexture = _this._blurTexture2.getInternalTexture();
  97794. if (internalTexture) {
  97795. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97796. }
  97797. }
  97798. });
  97799. // Prevent autoClear.
  97800. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97801. };
  97802. /**
  97803. * Checks for the readiness of the element composing the layer.
  97804. * @param subMesh the mesh to check for
  97805. * @param useInstances specify wether or not to use instances to render the mesh
  97806. * @param emissiveTexture the associated emissive texture used to generate the glow
  97807. * @return true if ready otherwise, false
  97808. */
  97809. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97810. var material = subMesh.getMaterial();
  97811. var mesh = subMesh.getRenderingMesh();
  97812. if (!material || !mesh) {
  97813. return false;
  97814. }
  97815. var emissiveTexture = material.emissiveTexture;
  97816. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97817. };
  97818. /**
  97819. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97820. */
  97821. GlowLayer.prototype.needStencil = function () {
  97822. return false;
  97823. };
  97824. /**
  97825. * Implementation specific of rendering the generating effect on the main canvas.
  97826. * @param effect The effect used to render through
  97827. */
  97828. GlowLayer.prototype._internalRender = function (effect) {
  97829. // Texture
  97830. effect.setTexture("textureSampler", this._blurTexture1);
  97831. effect.setTexture("textureSampler2", this._blurTexture2);
  97832. effect.setFloat("offset", this._intensity);
  97833. // Cache
  97834. var engine = this._engine;
  97835. var previousStencilBuffer = engine.getStencilBuffer();
  97836. // Draw order
  97837. engine.setStencilBuffer(false);
  97838. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97839. // Draw order
  97840. engine.setStencilBuffer(previousStencilBuffer);
  97841. };
  97842. /**
  97843. * Sets the required values for both the emissive texture and and the main color.
  97844. */
  97845. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97846. var textureLevel = 1.0;
  97847. if (this.customEmissiveTextureSelector) {
  97848. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97849. }
  97850. else {
  97851. if (material) {
  97852. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97853. if (this._emissiveTextureAndColor.texture) {
  97854. textureLevel = this._emissiveTextureAndColor.texture.level;
  97855. }
  97856. }
  97857. else {
  97858. this._emissiveTextureAndColor.texture = null;
  97859. }
  97860. }
  97861. if (this.customEmissiveColorSelector) {
  97862. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97863. }
  97864. else {
  97865. if (material.emissiveColor) {
  97866. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97867. }
  97868. else {
  97869. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97870. }
  97871. }
  97872. };
  97873. /**
  97874. * Returns true if the mesh should render, otherwise false.
  97875. * @param mesh The mesh to render
  97876. * @returns true if it should render otherwise false
  97877. */
  97878. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97879. return this.hasMesh(mesh);
  97880. };
  97881. /**
  97882. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97883. * @param mesh The mesh to exclude from the glow layer
  97884. */
  97885. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97886. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97887. this._excludedMeshes.push(mesh.uniqueId);
  97888. }
  97889. };
  97890. /**
  97891. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97892. * @param mesh The mesh to remove
  97893. */
  97894. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97895. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97896. if (index !== -1) {
  97897. this._excludedMeshes.splice(index, 1);
  97898. }
  97899. };
  97900. /**
  97901. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97902. * @param mesh The mesh to include in the glow layer
  97903. */
  97904. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97905. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97906. this._includedOnlyMeshes.push(mesh.uniqueId);
  97907. }
  97908. };
  97909. /**
  97910. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97911. * @param mesh The mesh to remove
  97912. */
  97913. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97914. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97915. if (index !== -1) {
  97916. this._includedOnlyMeshes.splice(index, 1);
  97917. }
  97918. };
  97919. /**
  97920. * Determine if a given mesh will be used in the glow layer
  97921. * @param mesh The mesh to test
  97922. * @returns true if the mesh will be highlighted by the current glow layer
  97923. */
  97924. GlowLayer.prototype.hasMesh = function (mesh) {
  97925. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97926. return false;
  97927. }
  97928. // Included Mesh
  97929. if (this._includedOnlyMeshes.length) {
  97930. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97931. }
  97932. ;
  97933. // Excluded Mesh
  97934. if (this._excludedMeshes.length) {
  97935. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97936. }
  97937. ;
  97938. return true;
  97939. };
  97940. /**
  97941. * Free any resources and references associated to a mesh.
  97942. * Internal use
  97943. * @param mesh The mesh to free.
  97944. */
  97945. GlowLayer.prototype._disposeMesh = function (mesh) {
  97946. this.removeIncludedOnlyMesh(mesh);
  97947. this.removeExcludedMesh(mesh);
  97948. };
  97949. /**
  97950. * Gets the class name of the effect layer
  97951. * @returns the string with the class name of the effect layer
  97952. */
  97953. GlowLayer.prototype.getClassName = function () {
  97954. return "GlowLayer";
  97955. };
  97956. /**
  97957. * Serializes this glow layer
  97958. * @returns a serialized glow layer object
  97959. */
  97960. GlowLayer.prototype.serialize = function () {
  97961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97962. serializationObject.customType = "BABYLON.GlowLayer";
  97963. var index;
  97964. // Included meshes
  97965. serializationObject.includedMeshes = [];
  97966. if (this._includedOnlyMeshes.length) {
  97967. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97968. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97969. if (mesh) {
  97970. serializationObject.includedMeshes.push(mesh.id);
  97971. }
  97972. }
  97973. }
  97974. // Excluded meshes
  97975. serializationObject.excludedMeshes = [];
  97976. if (this._excludedMeshes.length) {
  97977. for (index = 0; index < this._excludedMeshes.length; index++) {
  97978. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97979. if (mesh) {
  97980. serializationObject.excludedMeshes.push(mesh.id);
  97981. }
  97982. }
  97983. }
  97984. return serializationObject;
  97985. };
  97986. /**
  97987. * Creates a Glow Layer from parsed glow layer data
  97988. * @param parsedGlowLayer defines glow layer data
  97989. * @param scene defines the current scene
  97990. * @param rootUrl defines the root URL containing the glow layer information
  97991. * @returns a parsed Glow Layer
  97992. */
  97993. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97994. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97995. var index;
  97996. // Excluded meshes
  97997. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97998. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97999. if (mesh) {
  98000. gl.addExcludedMesh(mesh);
  98001. }
  98002. }
  98003. // Included meshes
  98004. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98005. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98006. if (mesh) {
  98007. gl.addIncludedOnlyMesh(mesh);
  98008. }
  98009. }
  98010. return gl;
  98011. };
  98012. /**
  98013. * Effect Name of the layer.
  98014. */
  98015. GlowLayer.EffectName = "GlowLayer";
  98016. /**
  98017. * The default blur kernel size used for the glow.
  98018. */
  98019. GlowLayer.DefaultBlurKernelSize = 32;
  98020. /**
  98021. * The default texture size ratio used for the glow.
  98022. */
  98023. GlowLayer.DefaultTextureRatio = 0.5;
  98024. __decorate([
  98025. BABYLON.serialize()
  98026. ], GlowLayer.prototype, "blurKernelSize", null);
  98027. __decorate([
  98028. BABYLON.serialize()
  98029. ], GlowLayer.prototype, "intensity", null);
  98030. __decorate([
  98031. BABYLON.serialize("options")
  98032. ], GlowLayer.prototype, "_options", void 0);
  98033. return GlowLayer;
  98034. }(BABYLON.EffectLayer));
  98035. BABYLON.GlowLayer = GlowLayer;
  98036. })(BABYLON || (BABYLON = {}));
  98037. //# sourceMappingURL=babylon.glowLayer.js.map
  98038. var BABYLON;
  98039. (function (BABYLON) {
  98040. /**
  98041. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98042. */
  98043. var AssetTaskState;
  98044. (function (AssetTaskState) {
  98045. /**
  98046. * Initialization
  98047. */
  98048. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98049. /**
  98050. * Running
  98051. */
  98052. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98053. /**
  98054. * Done
  98055. */
  98056. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98057. /**
  98058. * Error
  98059. */
  98060. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98061. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98062. /**
  98063. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98064. */
  98065. var AbstractAssetTask = /** @class */ (function () {
  98066. /**
  98067. * Creates a new {BABYLON.AssetsManager}
  98068. * @param name defines the name of the task
  98069. */
  98070. function AbstractAssetTask(
  98071. /**
  98072. * Task name
  98073. */ name) {
  98074. this.name = name;
  98075. this._isCompleted = false;
  98076. this._taskState = AssetTaskState.INIT;
  98077. }
  98078. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98079. /**
  98080. * Get if the task is completed
  98081. */
  98082. get: function () {
  98083. return this._isCompleted;
  98084. },
  98085. enumerable: true,
  98086. configurable: true
  98087. });
  98088. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98089. /**
  98090. * Gets the current state of the task
  98091. */
  98092. get: function () {
  98093. return this._taskState;
  98094. },
  98095. enumerable: true,
  98096. configurable: true
  98097. });
  98098. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98099. /**
  98100. * Gets the current error object (if task is in error)
  98101. */
  98102. get: function () {
  98103. return this._errorObject;
  98104. },
  98105. enumerable: true,
  98106. configurable: true
  98107. });
  98108. /**
  98109. * Internal only
  98110. * @hidden
  98111. */
  98112. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98113. if (this._errorObject) {
  98114. return;
  98115. }
  98116. this._errorObject = {
  98117. message: message,
  98118. exception: exception
  98119. };
  98120. };
  98121. /**
  98122. * Execute the current task
  98123. * @param scene defines the scene where you want your assets to be loaded
  98124. * @param onSuccess is a callback called when the task is successfully executed
  98125. * @param onError is a callback called if an error occurs
  98126. */
  98127. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98128. var _this = this;
  98129. this._taskState = AssetTaskState.RUNNING;
  98130. this.runTask(scene, function () {
  98131. _this.onDoneCallback(onSuccess, onError);
  98132. }, function (msg, exception) {
  98133. _this.onErrorCallback(onError, msg, exception);
  98134. });
  98135. };
  98136. /**
  98137. * Execute the current task
  98138. * @param scene defines the scene where you want your assets to be loaded
  98139. * @param onSuccess is a callback called when the task is successfully executed
  98140. * @param onError is a callback called if an error occurs
  98141. */
  98142. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98143. throw new Error("runTask is not implemented");
  98144. };
  98145. /**
  98146. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98147. * This can be used with failed tasks that have the reason for failure fixed.
  98148. */
  98149. AbstractAssetTask.prototype.reset = function () {
  98150. this._taskState = AssetTaskState.INIT;
  98151. };
  98152. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98153. this._taskState = AssetTaskState.ERROR;
  98154. this._errorObject = {
  98155. message: message,
  98156. exception: exception
  98157. };
  98158. if (this.onError) {
  98159. this.onError(this, message, exception);
  98160. }
  98161. onError();
  98162. };
  98163. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98164. try {
  98165. this._taskState = AssetTaskState.DONE;
  98166. this._isCompleted = true;
  98167. if (this.onSuccess) {
  98168. this.onSuccess(this);
  98169. }
  98170. onSuccess();
  98171. }
  98172. catch (e) {
  98173. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98174. }
  98175. };
  98176. return AbstractAssetTask;
  98177. }());
  98178. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98179. /**
  98180. * Class used to share progress information about assets loading
  98181. */
  98182. var AssetsProgressEvent = /** @class */ (function () {
  98183. /**
  98184. * Creates a {BABYLON.AssetsProgressEvent}
  98185. * @param remainingCount defines the number of remaining tasks to process
  98186. * @param totalCount defines the total number of tasks
  98187. * @param task defines the task that was just processed
  98188. */
  98189. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98190. this.remainingCount = remainingCount;
  98191. this.totalCount = totalCount;
  98192. this.task = task;
  98193. }
  98194. return AssetsProgressEvent;
  98195. }());
  98196. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98197. /**
  98198. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98199. */
  98200. var MeshAssetTask = /** @class */ (function (_super) {
  98201. __extends(MeshAssetTask, _super);
  98202. /**
  98203. * Creates a new {BABYLON.MeshAssetTask}
  98204. * @param name defines the name of the task
  98205. * @param meshesNames defines the list of mesh's names you want to load
  98206. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98207. * @param sceneFilename defines the filename of the scene to load from
  98208. */
  98209. function MeshAssetTask(
  98210. /**
  98211. * Defines the name of the task
  98212. */
  98213. name,
  98214. /**
  98215. * Defines the list of mesh's names you want to load
  98216. */
  98217. meshesNames,
  98218. /**
  98219. * Defines the root url to use as a base to load your meshes and associated resources
  98220. */
  98221. rootUrl,
  98222. /**
  98223. * Defines the filename of the scene to load from
  98224. */
  98225. sceneFilename) {
  98226. var _this = _super.call(this, name) || this;
  98227. _this.name = name;
  98228. _this.meshesNames = meshesNames;
  98229. _this.rootUrl = rootUrl;
  98230. _this.sceneFilename = sceneFilename;
  98231. return _this;
  98232. }
  98233. /**
  98234. * Execute the current task
  98235. * @param scene defines the scene where you want your assets to be loaded
  98236. * @param onSuccess is a callback called when the task is successfully executed
  98237. * @param onError is a callback called if an error occurs
  98238. */
  98239. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98240. var _this = this;
  98241. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98242. _this.loadedMeshes = meshes;
  98243. _this.loadedParticleSystems = particleSystems;
  98244. _this.loadedSkeletons = skeletons;
  98245. onSuccess();
  98246. }, null, function (scene, message, exception) {
  98247. onError(message, exception);
  98248. });
  98249. };
  98250. return MeshAssetTask;
  98251. }(AbstractAssetTask));
  98252. BABYLON.MeshAssetTask = MeshAssetTask;
  98253. /**
  98254. * Define a task used by {BABYLON.AssetsManager} to load text content
  98255. */
  98256. var TextFileAssetTask = /** @class */ (function (_super) {
  98257. __extends(TextFileAssetTask, _super);
  98258. /**
  98259. * Creates a new TextFileAssetTask object
  98260. * @param name defines the name of the task
  98261. * @param url defines the location of the file to load
  98262. */
  98263. function TextFileAssetTask(
  98264. /**
  98265. * Defines the name of the task
  98266. */
  98267. name,
  98268. /**
  98269. * Defines the location of the file to load
  98270. */
  98271. url) {
  98272. var _this = _super.call(this, name) || this;
  98273. _this.name = name;
  98274. _this.url = url;
  98275. return _this;
  98276. }
  98277. /**
  98278. * Execute the current task
  98279. * @param scene defines the scene where you want your assets to be loaded
  98280. * @param onSuccess is a callback called when the task is successfully executed
  98281. * @param onError is a callback called if an error occurs
  98282. */
  98283. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98284. var _this = this;
  98285. scene._loadFile(this.url, function (data) {
  98286. _this.text = data;
  98287. onSuccess();
  98288. }, undefined, false, false, function (request, exception) {
  98289. if (request) {
  98290. onError(request.status + " " + request.statusText, exception);
  98291. }
  98292. });
  98293. };
  98294. return TextFileAssetTask;
  98295. }(AbstractAssetTask));
  98296. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98297. /**
  98298. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98299. */
  98300. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98301. __extends(BinaryFileAssetTask, _super);
  98302. /**
  98303. * Creates a new BinaryFileAssetTask object
  98304. * @param name defines the name of the new task
  98305. * @param url defines the location of the file to load
  98306. */
  98307. function BinaryFileAssetTask(
  98308. /**
  98309. * Defines the name of the task
  98310. */
  98311. name,
  98312. /**
  98313. * Defines the location of the file to load
  98314. */
  98315. url) {
  98316. var _this = _super.call(this, name) || this;
  98317. _this.name = name;
  98318. _this.url = url;
  98319. return _this;
  98320. }
  98321. /**
  98322. * Execute the current task
  98323. * @param scene defines the scene where you want your assets to be loaded
  98324. * @param onSuccess is a callback called when the task is successfully executed
  98325. * @param onError is a callback called if an error occurs
  98326. */
  98327. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98328. var _this = this;
  98329. scene._loadFile(this.url, function (data) {
  98330. _this.data = data;
  98331. onSuccess();
  98332. }, undefined, true, true, function (request, exception) {
  98333. if (request) {
  98334. onError(request.status + " " + request.statusText, exception);
  98335. }
  98336. });
  98337. };
  98338. return BinaryFileAssetTask;
  98339. }(AbstractAssetTask));
  98340. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98341. /**
  98342. * Define a task used by {BABYLON.AssetsManager} to load images
  98343. */
  98344. var ImageAssetTask = /** @class */ (function (_super) {
  98345. __extends(ImageAssetTask, _super);
  98346. /**
  98347. * Creates a new ImageAssetTask
  98348. * @param name defines the name of the task
  98349. * @param url defines the location of the image to load
  98350. */
  98351. function ImageAssetTask(
  98352. /**
  98353. * Defines the name of the task
  98354. */
  98355. name,
  98356. /**
  98357. * Defines the location of the image to load
  98358. */
  98359. url) {
  98360. var _this = _super.call(this, name) || this;
  98361. _this.name = name;
  98362. _this.url = url;
  98363. return _this;
  98364. }
  98365. /**
  98366. * Execute the current task
  98367. * @param scene defines the scene where you want your assets to be loaded
  98368. * @param onSuccess is a callback called when the task is successfully executed
  98369. * @param onError is a callback called if an error occurs
  98370. */
  98371. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98372. var _this = this;
  98373. var img = new Image();
  98374. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98375. img.onload = function () {
  98376. _this.image = img;
  98377. onSuccess();
  98378. };
  98379. img.onerror = function (err) {
  98380. onError("Error loading image", err);
  98381. };
  98382. img.src = this.url;
  98383. };
  98384. return ImageAssetTask;
  98385. }(AbstractAssetTask));
  98386. BABYLON.ImageAssetTask = ImageAssetTask;
  98387. /**
  98388. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98389. */
  98390. var TextureAssetTask = /** @class */ (function (_super) {
  98391. __extends(TextureAssetTask, _super);
  98392. /**
  98393. * Creates a new TextureAssetTask object
  98394. * @param name defines the name of the task
  98395. * @param url defines the location of the file to load
  98396. * @param noMipmap defines if mipmap should not be generated (default is false)
  98397. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98398. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98399. */
  98400. function TextureAssetTask(
  98401. /**
  98402. * Defines the name of the task
  98403. */
  98404. name,
  98405. /**
  98406. * Defines the location of the file to load
  98407. */
  98408. url,
  98409. /**
  98410. * Defines if mipmap should not be generated (default is false)
  98411. */
  98412. noMipmap,
  98413. /**
  98414. * Defines if texture must be inverted on Y axis (default is false)
  98415. */
  98416. invertY,
  98417. /**
  98418. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98419. */
  98420. samplingMode) {
  98421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98422. var _this = _super.call(this, name) || this;
  98423. _this.name = name;
  98424. _this.url = url;
  98425. _this.noMipmap = noMipmap;
  98426. _this.invertY = invertY;
  98427. _this.samplingMode = samplingMode;
  98428. return _this;
  98429. }
  98430. /**
  98431. * Execute the current task
  98432. * @param scene defines the scene where you want your assets to be loaded
  98433. * @param onSuccess is a callback called when the task is successfully executed
  98434. * @param onError is a callback called if an error occurs
  98435. */
  98436. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98437. var onload = function () {
  98438. onSuccess();
  98439. };
  98440. var onerror = function (message, exception) {
  98441. onError(message, exception);
  98442. };
  98443. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98444. };
  98445. return TextureAssetTask;
  98446. }(AbstractAssetTask));
  98447. BABYLON.TextureAssetTask = TextureAssetTask;
  98448. /**
  98449. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98450. */
  98451. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98452. __extends(CubeTextureAssetTask, _super);
  98453. /**
  98454. * Creates a new CubeTextureAssetTask
  98455. * @param name defines the name of the task
  98456. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98457. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98458. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98459. * @param files defines the explicit list of files (undefined by default)
  98460. */
  98461. function CubeTextureAssetTask(
  98462. /**
  98463. * Defines the name of the task
  98464. */
  98465. name,
  98466. /**
  98467. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98468. */
  98469. url,
  98470. /**
  98471. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98472. */
  98473. extensions,
  98474. /**
  98475. * Defines if mipmaps should not be generated (default is false)
  98476. */
  98477. noMipmap,
  98478. /**
  98479. * Defines the explicit list of files (undefined by default)
  98480. */
  98481. files) {
  98482. var _this = _super.call(this, name) || this;
  98483. _this.name = name;
  98484. _this.url = url;
  98485. _this.extensions = extensions;
  98486. _this.noMipmap = noMipmap;
  98487. _this.files = files;
  98488. return _this;
  98489. }
  98490. /**
  98491. * Execute the current task
  98492. * @param scene defines the scene where you want your assets to be loaded
  98493. * @param onSuccess is a callback called when the task is successfully executed
  98494. * @param onError is a callback called if an error occurs
  98495. */
  98496. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98497. var onload = function () {
  98498. onSuccess();
  98499. };
  98500. var onerror = function (message, exception) {
  98501. onError(message, exception);
  98502. };
  98503. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98504. };
  98505. return CubeTextureAssetTask;
  98506. }(AbstractAssetTask));
  98507. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98508. /**
  98509. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98510. */
  98511. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98512. __extends(HDRCubeTextureAssetTask, _super);
  98513. /**
  98514. * Creates a new HDRCubeTextureAssetTask object
  98515. * @param name defines the name of the task
  98516. * @param url defines the location of the file to load
  98517. * @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.
  98518. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98519. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98520. * @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)
  98521. * @param reserved Internal use only
  98522. */
  98523. function HDRCubeTextureAssetTask(
  98524. /**
  98525. * Defines the name of the task
  98526. */
  98527. name,
  98528. /**
  98529. * Defines the location of the file to load
  98530. */
  98531. url,
  98532. /**
  98533. * Defines the desired size (the more it increases the longer the generation will be)
  98534. */
  98535. size,
  98536. /**
  98537. * Defines if mipmaps should not be generated (default is false)
  98538. */
  98539. noMipmap,
  98540. /**
  98541. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98542. */
  98543. generateHarmonics,
  98544. /**
  98545. * 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)
  98546. */
  98547. gammaSpace,
  98548. /**
  98549. * Internal Use Only
  98550. */
  98551. reserved) {
  98552. if (noMipmap === void 0) { noMipmap = false; }
  98553. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98554. if (gammaSpace === void 0) { gammaSpace = false; }
  98555. if (reserved === void 0) { reserved = false; }
  98556. var _this = _super.call(this, name) || this;
  98557. _this.name = name;
  98558. _this.url = url;
  98559. _this.size = size;
  98560. _this.noMipmap = noMipmap;
  98561. _this.generateHarmonics = generateHarmonics;
  98562. _this.gammaSpace = gammaSpace;
  98563. _this.reserved = reserved;
  98564. return _this;
  98565. }
  98566. /**
  98567. * Execute the current task
  98568. * @param scene defines the scene where you want your assets to be loaded
  98569. * @param onSuccess is a callback called when the task is successfully executed
  98570. * @param onError is a callback called if an error occurs
  98571. */
  98572. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98573. var onload = function () {
  98574. onSuccess();
  98575. };
  98576. var onerror = function (message, exception) {
  98577. onError(message, exception);
  98578. };
  98579. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98580. };
  98581. return HDRCubeTextureAssetTask;
  98582. }(AbstractAssetTask));
  98583. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98584. /**
  98585. * This class can be used to easily import assets into a scene
  98586. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98587. */
  98588. var AssetsManager = /** @class */ (function () {
  98589. /**
  98590. * Creates a new AssetsManager
  98591. * @param scene defines the scene to work on
  98592. */
  98593. function AssetsManager(scene) {
  98594. this._isLoading = false;
  98595. this._tasks = new Array();
  98596. this._waitingTasksCount = 0;
  98597. this._totalTasksCount = 0;
  98598. /**
  98599. * Observable called when all tasks are processed
  98600. */
  98601. this.onTaskSuccessObservable = new BABYLON.Observable();
  98602. /**
  98603. * Observable called when a task had an error
  98604. */
  98605. this.onTaskErrorObservable = new BABYLON.Observable();
  98606. /**
  98607. * Observable called when a task is successful
  98608. */
  98609. this.onTasksDoneObservable = new BABYLON.Observable();
  98610. /**
  98611. * Observable called when a task is done (whatever the result is)
  98612. */
  98613. this.onProgressObservable = new BABYLON.Observable();
  98614. /**
  98615. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98616. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98617. */
  98618. this.useDefaultLoadingScreen = true;
  98619. this._scene = scene;
  98620. }
  98621. /**
  98622. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98623. * @param taskName defines the name of the new task
  98624. * @param meshesNames defines the name of meshes to load
  98625. * @param rootUrl defines the root url to use to locate files
  98626. * @param sceneFilename defines the filename of the scene file
  98627. * @returns a new {BABYLON.MeshAssetTask} object
  98628. */
  98629. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98630. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98631. this._tasks.push(task);
  98632. return task;
  98633. };
  98634. /**
  98635. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98636. * @param taskName defines the name of the new task
  98637. * @param url defines the url of the file to load
  98638. * @returns a new {BABYLON.TextFileAssetTask} object
  98639. */
  98640. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98641. var task = new TextFileAssetTask(taskName, url);
  98642. this._tasks.push(task);
  98643. return task;
  98644. };
  98645. /**
  98646. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98647. * @param taskName defines the name of the new task
  98648. * @param url defines the url of the file to load
  98649. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98650. */
  98651. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98652. var task = new BinaryFileAssetTask(taskName, url);
  98653. this._tasks.push(task);
  98654. return task;
  98655. };
  98656. /**
  98657. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98658. * @param taskName defines the name of the new task
  98659. * @param url defines the url of the file to load
  98660. * @returns a new {BABYLON.ImageAssetTask} object
  98661. */
  98662. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98663. var task = new ImageAssetTask(taskName, url);
  98664. this._tasks.push(task);
  98665. return task;
  98666. };
  98667. /**
  98668. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98669. * @param taskName defines the name of the new task
  98670. * @param url defines the url of the file to load
  98671. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98672. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98673. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98674. * @returns a new {BABYLON.TextureAssetTask} object
  98675. */
  98676. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98677. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98678. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98679. this._tasks.push(task);
  98680. return task;
  98681. };
  98682. /**
  98683. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98684. * @param taskName defines the name of the new task
  98685. * @param url defines the url of the file to load
  98686. * @param extensions defines the extension to use to load the cube map (can be null)
  98687. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98688. * @param files defines the list of files to load (can be null)
  98689. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98690. */
  98691. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98692. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98693. this._tasks.push(task);
  98694. return task;
  98695. };
  98696. /**
  98697. *
  98698. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98699. * @param taskName defines the name of the new task
  98700. * @param url defines the url of the file to load
  98701. * @param size defines the size you want for the cubemap (can be null)
  98702. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98703. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98704. * @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)
  98705. * @param reserved Internal use only
  98706. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98707. */
  98708. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98709. if (noMipmap === void 0) { noMipmap = false; }
  98710. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98711. if (gammaSpace === void 0) { gammaSpace = false; }
  98712. if (reserved === void 0) { reserved = false; }
  98713. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98714. this._tasks.push(task);
  98715. return task;
  98716. };
  98717. /**
  98718. * Remove a task from the assets manager.
  98719. * @param task the task to remove
  98720. */
  98721. AssetsManager.prototype.removeTask = function (task) {
  98722. var index = this._tasks.indexOf(task);
  98723. if (index > -1) {
  98724. this._tasks.splice(index, 1);
  98725. }
  98726. };
  98727. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98728. this._waitingTasksCount--;
  98729. try {
  98730. if (this.onProgress) {
  98731. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98732. }
  98733. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98734. }
  98735. catch (e) {
  98736. BABYLON.Tools.Error("Error running progress callbacks.");
  98737. console.log(e);
  98738. }
  98739. if (this._waitingTasksCount === 0) {
  98740. try {
  98741. if (this.onFinish) {
  98742. this.onFinish(this._tasks);
  98743. }
  98744. // Let's remove successfull tasks
  98745. var currentTasks = this._tasks.slice();
  98746. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98747. var task = currentTasks_1[_i];
  98748. if (task.taskState === AssetTaskState.DONE) {
  98749. var index = this._tasks.indexOf(task);
  98750. if (index > -1) {
  98751. this._tasks.splice(index, 1);
  98752. }
  98753. }
  98754. }
  98755. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98756. }
  98757. catch (e) {
  98758. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98759. console.log(e);
  98760. }
  98761. this._isLoading = false;
  98762. this._scene.getEngine().hideLoadingUI();
  98763. }
  98764. };
  98765. AssetsManager.prototype._runTask = function (task) {
  98766. var _this = this;
  98767. var done = function () {
  98768. try {
  98769. if (_this.onTaskSuccess) {
  98770. _this.onTaskSuccess(task);
  98771. }
  98772. _this.onTaskSuccessObservable.notifyObservers(task);
  98773. _this._decreaseWaitingTasksCount(task);
  98774. }
  98775. catch (e) {
  98776. error("Error executing task success callbacks", e);
  98777. }
  98778. };
  98779. var error = function (message, exception) {
  98780. task._setErrorObject(message, exception);
  98781. if (_this.onTaskError) {
  98782. _this.onTaskError(task);
  98783. }
  98784. _this.onTaskErrorObservable.notifyObservers(task);
  98785. _this._decreaseWaitingTasksCount(task);
  98786. };
  98787. task.run(this._scene, done, error);
  98788. };
  98789. /**
  98790. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98791. * @return the current instance of the {BABYLON.AssetsManager}
  98792. */
  98793. AssetsManager.prototype.reset = function () {
  98794. this._isLoading = false;
  98795. this._tasks = new Array();
  98796. return this;
  98797. };
  98798. /**
  98799. * Start the loading process
  98800. * @return the current instance of the {BABYLON.AssetsManager}
  98801. */
  98802. AssetsManager.prototype.load = function () {
  98803. if (this._isLoading) {
  98804. return this;
  98805. }
  98806. this._isLoading = true;
  98807. this._waitingTasksCount = this._tasks.length;
  98808. this._totalTasksCount = this._tasks.length;
  98809. if (this._waitingTasksCount === 0) {
  98810. this._isLoading = false;
  98811. if (this.onFinish) {
  98812. this.onFinish(this._tasks);
  98813. }
  98814. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98815. return this;
  98816. }
  98817. if (this.useDefaultLoadingScreen) {
  98818. this._scene.getEngine().displayLoadingUI();
  98819. }
  98820. for (var index = 0; index < this._tasks.length; index++) {
  98821. var task = this._tasks[index];
  98822. if (task.taskState === AssetTaskState.INIT) {
  98823. this._runTask(task);
  98824. }
  98825. }
  98826. return this;
  98827. };
  98828. return AssetsManager;
  98829. }());
  98830. BABYLON.AssetsManager = AssetsManager;
  98831. })(BABYLON || (BABYLON = {}));
  98832. //# sourceMappingURL=babylon.assetsManager.js.map
  98833. var BABYLON;
  98834. (function (BABYLON) {
  98835. var serializedGeometries = [];
  98836. var serializeGeometry = function (geometry, serializationGeometries) {
  98837. if (serializedGeometries[geometry.id]) {
  98838. return;
  98839. }
  98840. if (geometry.doNotSerialize) {
  98841. return;
  98842. }
  98843. if (geometry instanceof BABYLON.BoxGeometry) {
  98844. serializationGeometries.boxes.push(geometry.serialize());
  98845. }
  98846. else if (geometry instanceof BABYLON.SphereGeometry) {
  98847. serializationGeometries.spheres.push(geometry.serialize());
  98848. }
  98849. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98850. serializationGeometries.cylinders.push(geometry.serialize());
  98851. }
  98852. else if (geometry instanceof BABYLON.TorusGeometry) {
  98853. serializationGeometries.toruses.push(geometry.serialize());
  98854. }
  98855. else if (geometry instanceof BABYLON.GroundGeometry) {
  98856. serializationGeometries.grounds.push(geometry.serialize());
  98857. }
  98858. else if (geometry instanceof BABYLON.Plane) {
  98859. serializationGeometries.planes.push(geometry.serialize());
  98860. }
  98861. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98862. serializationGeometries.torusKnots.push(geometry.serialize());
  98863. }
  98864. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98865. throw new Error("Unknown primitive type");
  98866. }
  98867. else {
  98868. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98869. }
  98870. serializedGeometries[geometry.id] = true;
  98871. };
  98872. var serializeMesh = function (mesh, serializationScene) {
  98873. var serializationObject = {};
  98874. // Geometry
  98875. var geometry = mesh._geometry;
  98876. if (geometry) {
  98877. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98878. // 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
  98879. serializeGeometry(geometry, serializationScene.geometries);
  98880. }
  98881. }
  98882. // Custom
  98883. if (mesh.serialize) {
  98884. mesh.serialize(serializationObject);
  98885. }
  98886. return serializationObject;
  98887. };
  98888. var finalizeSingleMesh = function (mesh, serializationObject) {
  98889. //only works if the mesh is already loaded
  98890. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98891. //serialize material
  98892. if (mesh.material) {
  98893. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98894. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98895. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98896. serializationObject.multiMaterials.push(mesh.material.serialize());
  98897. }
  98898. }
  98899. else {
  98900. serializationObject.materials = serializationObject.materials || [];
  98901. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98902. serializationObject.materials.push(mesh.material.serialize());
  98903. }
  98904. }
  98905. }
  98906. //serialize geometry
  98907. var geometry = mesh._geometry;
  98908. if (geometry) {
  98909. if (!serializationObject.geometries) {
  98910. serializationObject.geometries = {};
  98911. serializationObject.geometries.boxes = [];
  98912. serializationObject.geometries.spheres = [];
  98913. serializationObject.geometries.cylinders = [];
  98914. serializationObject.geometries.toruses = [];
  98915. serializationObject.geometries.grounds = [];
  98916. serializationObject.geometries.planes = [];
  98917. serializationObject.geometries.torusKnots = [];
  98918. serializationObject.geometries.vertexData = [];
  98919. }
  98920. serializeGeometry(geometry, serializationObject.geometries);
  98921. }
  98922. // Skeletons
  98923. if (mesh.skeleton) {
  98924. serializationObject.skeletons = serializationObject.skeletons || [];
  98925. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98926. }
  98927. //serialize the actual mesh
  98928. serializationObject.meshes = serializationObject.meshes || [];
  98929. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98930. }
  98931. };
  98932. var SceneSerializer = /** @class */ (function () {
  98933. function SceneSerializer() {
  98934. }
  98935. SceneSerializer.ClearCache = function () {
  98936. serializedGeometries = [];
  98937. };
  98938. SceneSerializer.Serialize = function (scene) {
  98939. var serializationObject = {};
  98940. SceneSerializer.ClearCache();
  98941. // Scene
  98942. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98943. serializationObject.autoClear = scene.autoClear;
  98944. serializationObject.clearColor = scene.clearColor.asArray();
  98945. serializationObject.ambientColor = scene.ambientColor.asArray();
  98946. serializationObject.gravity = scene.gravity.asArray();
  98947. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98948. serializationObject.workerCollisions = scene.workerCollisions;
  98949. // Fog
  98950. if (scene.fogMode && scene.fogMode !== 0) {
  98951. serializationObject.fogMode = scene.fogMode;
  98952. serializationObject.fogColor = scene.fogColor.asArray();
  98953. serializationObject.fogStart = scene.fogStart;
  98954. serializationObject.fogEnd = scene.fogEnd;
  98955. serializationObject.fogDensity = scene.fogDensity;
  98956. }
  98957. //Physics
  98958. if (scene.isPhysicsEnabled()) {
  98959. var physicEngine = scene.getPhysicsEngine();
  98960. if (physicEngine) {
  98961. serializationObject.physicsEnabled = true;
  98962. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98963. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98964. }
  98965. }
  98966. // Metadata
  98967. if (scene.metadata) {
  98968. serializationObject.metadata = scene.metadata;
  98969. }
  98970. // Morph targets
  98971. serializationObject.morphTargetManagers = [];
  98972. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98973. var abstractMesh = _a[_i];
  98974. var manager = abstractMesh.morphTargetManager;
  98975. if (manager) {
  98976. serializationObject.morphTargetManagers.push(manager.serialize());
  98977. }
  98978. }
  98979. // Lights
  98980. serializationObject.lights = [];
  98981. var index;
  98982. var light;
  98983. for (index = 0; index < scene.lights.length; index++) {
  98984. light = scene.lights[index];
  98985. if (!light.doNotSerialize) {
  98986. serializationObject.lights.push(light.serialize());
  98987. }
  98988. }
  98989. // Cameras
  98990. serializationObject.cameras = [];
  98991. for (index = 0; index < scene.cameras.length; index++) {
  98992. var camera = scene.cameras[index];
  98993. if (!camera.doNotSerialize) {
  98994. serializationObject.cameras.push(camera.serialize());
  98995. }
  98996. }
  98997. if (scene.activeCamera) {
  98998. serializationObject.activeCameraID = scene.activeCamera.id;
  98999. }
  99000. // Animations
  99001. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99002. // Materials
  99003. serializationObject.materials = [];
  99004. serializationObject.multiMaterials = [];
  99005. var material;
  99006. for (index = 0; index < scene.materials.length; index++) {
  99007. material = scene.materials[index];
  99008. if (!material.doNotSerialize) {
  99009. serializationObject.materials.push(material.serialize());
  99010. }
  99011. }
  99012. // MultiMaterials
  99013. serializationObject.multiMaterials = [];
  99014. for (index = 0; index < scene.multiMaterials.length; index++) {
  99015. var multiMaterial = scene.multiMaterials[index];
  99016. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99017. }
  99018. // Environment texture
  99019. if (scene.environmentTexture) {
  99020. serializationObject.environmentTexture = scene.environmentTexture.name;
  99021. }
  99022. // Skeletons
  99023. serializationObject.skeletons = [];
  99024. for (index = 0; index < scene.skeletons.length; index++) {
  99025. var skeleton = scene.skeletons[index];
  99026. if (!skeleton.doNotSerialize) {
  99027. serializationObject.skeletons.push(skeleton.serialize());
  99028. }
  99029. }
  99030. // Transform nodes
  99031. serializationObject.transformNodes = [];
  99032. for (index = 0; index < scene.transformNodes.length; index++) {
  99033. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99034. }
  99035. // Geometries
  99036. serializationObject.geometries = {};
  99037. serializationObject.geometries.boxes = [];
  99038. serializationObject.geometries.spheres = [];
  99039. serializationObject.geometries.cylinders = [];
  99040. serializationObject.geometries.toruses = [];
  99041. serializationObject.geometries.grounds = [];
  99042. serializationObject.geometries.planes = [];
  99043. serializationObject.geometries.torusKnots = [];
  99044. serializationObject.geometries.vertexData = [];
  99045. serializedGeometries = [];
  99046. var geometries = scene.getGeometries();
  99047. for (index = 0; index < geometries.length; index++) {
  99048. var geometry = geometries[index];
  99049. if (geometry.isReady()) {
  99050. serializeGeometry(geometry, serializationObject.geometries);
  99051. }
  99052. }
  99053. // Meshes
  99054. serializationObject.meshes = [];
  99055. for (index = 0; index < scene.meshes.length; index++) {
  99056. var abstractMesh = scene.meshes[index];
  99057. if (abstractMesh instanceof BABYLON.Mesh) {
  99058. var mesh = abstractMesh;
  99059. if (!mesh.doNotSerialize) {
  99060. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99061. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99062. }
  99063. }
  99064. }
  99065. }
  99066. // Particles Systems
  99067. serializationObject.particleSystems = [];
  99068. for (index = 0; index < scene.particleSystems.length; index++) {
  99069. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99070. }
  99071. // Shadows
  99072. serializationObject.shadowGenerators = [];
  99073. for (index = 0; index < scene.lights.length; index++) {
  99074. light = scene.lights[index];
  99075. var shadowGenerator = light.getShadowGenerator();
  99076. if (shadowGenerator) {
  99077. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99078. }
  99079. }
  99080. // Action Manager
  99081. if (scene.actionManager) {
  99082. serializationObject.actions = scene.actionManager.serialize("scene");
  99083. }
  99084. // Audio
  99085. serializationObject.sounds = [];
  99086. for (index = 0; index < scene.soundTracks.length; index++) {
  99087. var soundtrack = scene.soundTracks[index];
  99088. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99089. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99090. }
  99091. }
  99092. // Components
  99093. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99094. var component = _c[_b];
  99095. component.serialize(serializationObject);
  99096. }
  99097. return serializationObject;
  99098. };
  99099. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99100. if (withParents === void 0) { withParents = false; }
  99101. if (withChildren === void 0) { withChildren = false; }
  99102. var serializationObject = {};
  99103. SceneSerializer.ClearCache();
  99104. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99105. if (withParents || withChildren) {
  99106. //deliberate for loop! not for each, appended should be processed as well.
  99107. for (var i = 0; i < toSerialize.length; ++i) {
  99108. if (withChildren) {
  99109. toSerialize[i].getDescendants().forEach(function (node) {
  99110. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99111. toSerialize.push(node);
  99112. }
  99113. });
  99114. }
  99115. //make sure the array doesn't contain the object already
  99116. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99117. toSerialize.push(toSerialize[i].parent);
  99118. }
  99119. }
  99120. }
  99121. toSerialize.forEach(function (mesh) {
  99122. finalizeSingleMesh(mesh, serializationObject);
  99123. });
  99124. return serializationObject;
  99125. };
  99126. return SceneSerializer;
  99127. }());
  99128. BABYLON.SceneSerializer = SceneSerializer;
  99129. })(BABYLON || (BABYLON = {}));
  99130. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99131. var BABYLON;
  99132. (function (BABYLON) {
  99133. var ReflectionProbe = /** @class */ (function () {
  99134. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99136. var _this = this;
  99137. this.name = name;
  99138. this._viewMatrix = BABYLON.Matrix.Identity();
  99139. this._target = BABYLON.Vector3.Zero();
  99140. this._add = BABYLON.Vector3.Zero();
  99141. this._invertYAxis = false;
  99142. this.position = BABYLON.Vector3.Zero();
  99143. this._scene = scene;
  99144. this._scene.reflectionProbes.push(this);
  99145. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99146. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99147. switch (faceIndex) {
  99148. case 0:
  99149. _this._add.copyFromFloats(1, 0, 0);
  99150. break;
  99151. case 1:
  99152. _this._add.copyFromFloats(-1, 0, 0);
  99153. break;
  99154. case 2:
  99155. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99156. break;
  99157. case 3:
  99158. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99159. break;
  99160. case 4:
  99161. _this._add.copyFromFloats(0, 0, 1);
  99162. break;
  99163. case 5:
  99164. _this._add.copyFromFloats(0, 0, -1);
  99165. break;
  99166. }
  99167. if (_this._attachedMesh) {
  99168. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99169. }
  99170. _this.position.addToRef(_this._add, _this._target);
  99171. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99172. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99173. scene._forcedViewPosition = _this.position;
  99174. });
  99175. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99176. scene._forcedViewPosition = null;
  99177. scene.updateTransformMatrix(true);
  99178. });
  99179. if (scene.activeCamera) {
  99180. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99181. }
  99182. }
  99183. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99184. get: function () {
  99185. return this._renderTargetTexture.samples;
  99186. },
  99187. set: function (value) {
  99188. this._renderTargetTexture.samples = value;
  99189. },
  99190. enumerable: true,
  99191. configurable: true
  99192. });
  99193. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99194. get: function () {
  99195. return this._renderTargetTexture.refreshRate;
  99196. },
  99197. set: function (value) {
  99198. this._renderTargetTexture.refreshRate = value;
  99199. },
  99200. enumerable: true,
  99201. configurable: true
  99202. });
  99203. ReflectionProbe.prototype.getScene = function () {
  99204. return this._scene;
  99205. };
  99206. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99207. get: function () {
  99208. return this._renderTargetTexture;
  99209. },
  99210. enumerable: true,
  99211. configurable: true
  99212. });
  99213. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99214. get: function () {
  99215. return this._renderTargetTexture.renderList;
  99216. },
  99217. enumerable: true,
  99218. configurable: true
  99219. });
  99220. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99221. this._attachedMesh = mesh;
  99222. };
  99223. /**
  99224. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99225. *
  99226. * @param renderingGroupId The rendering group id corresponding to its index
  99227. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99228. */
  99229. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99230. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99231. };
  99232. ReflectionProbe.prototype.dispose = function () {
  99233. var index = this._scene.reflectionProbes.indexOf(this);
  99234. if (index !== -1) {
  99235. // Remove from the scene if found
  99236. this._scene.reflectionProbes.splice(index, 1);
  99237. }
  99238. if (this._renderTargetTexture) {
  99239. this._renderTargetTexture.dispose();
  99240. this._renderTargetTexture = null;
  99241. }
  99242. };
  99243. return ReflectionProbe;
  99244. }());
  99245. BABYLON.ReflectionProbe = ReflectionProbe;
  99246. })(BABYLON || (BABYLON = {}));
  99247. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99248. var BABYLON;
  99249. (function (BABYLON) {
  99250. /**
  99251. * Defines the layer scene component responsible to manage any layers
  99252. * in a given scene.
  99253. */
  99254. var LayerSceneComponent = /** @class */ (function () {
  99255. /**
  99256. * Creates a new instance of the component for the given scene
  99257. * @param scene Defines the scene to register the component in
  99258. */
  99259. function LayerSceneComponent(scene) {
  99260. /**
  99261. * The component name helpfull to identify the component in the list of scene components.
  99262. */
  99263. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99264. this.scene = scene;
  99265. this._engine = scene.getEngine();
  99266. scene.layers = new Array();
  99267. }
  99268. /**
  99269. * Registers the component in a given scene
  99270. */
  99271. LayerSceneComponent.prototype.register = function () {
  99272. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99273. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99274. };
  99275. /**
  99276. * Rebuilds the elements related to this component in case of
  99277. * context lost for instance.
  99278. */
  99279. LayerSceneComponent.prototype.rebuild = function () {
  99280. var layers = this.scene.layers;
  99281. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99282. var layer = layers_1[_i];
  99283. layer._rebuild();
  99284. }
  99285. };
  99286. /**
  99287. * Disposes the component and the associated ressources.
  99288. */
  99289. LayerSceneComponent.prototype.dispose = function () {
  99290. var layers = this.scene.layers;
  99291. while (layers.length) {
  99292. layers[0].dispose();
  99293. }
  99294. };
  99295. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99296. var layers = this.scene.layers;
  99297. if (layers.length) {
  99298. this._engine.setDepthBuffer(false);
  99299. var cameraLayerMask = camera.layerMask;
  99300. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99301. var layer = layers_2[_i];
  99302. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99303. layer.render();
  99304. }
  99305. }
  99306. this._engine.setDepthBuffer(true);
  99307. }
  99308. };
  99309. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99310. this._draw(camera, true);
  99311. };
  99312. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99313. this._draw(camera, false);
  99314. };
  99315. return LayerSceneComponent;
  99316. }());
  99317. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99318. })(BABYLON || (BABYLON = {}));
  99319. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99320. var BABYLON;
  99321. (function (BABYLON) {
  99322. var Layer = /** @class */ (function () {
  99323. function Layer(name, imgUrl, scene, isBackground, color) {
  99324. this.name = name;
  99325. this.scale = new BABYLON.Vector2(1, 1);
  99326. this.offset = new BABYLON.Vector2(0, 0);
  99327. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99328. this.layerMask = 0x0FFFFFFF;
  99329. this._vertexBuffers = {};
  99330. // Events
  99331. /**
  99332. * An event triggered when the layer is disposed.
  99333. */
  99334. this.onDisposeObservable = new BABYLON.Observable();
  99335. /**
  99336. * An event triggered before rendering the scene
  99337. */
  99338. this.onBeforeRenderObservable = new BABYLON.Observable();
  99339. /**
  99340. * An event triggered after rendering the scene
  99341. */
  99342. this.onAfterRenderObservable = new BABYLON.Observable();
  99343. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99344. this.isBackground = isBackground === undefined ? true : isBackground;
  99345. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99346. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99347. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99348. if (!layerComponent) {
  99349. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99350. this._scene._addComponent(layerComponent);
  99351. }
  99352. this._scene.layers.push(this);
  99353. var engine = this._scene.getEngine();
  99354. // VBO
  99355. var vertices = [];
  99356. vertices.push(1, 1);
  99357. vertices.push(-1, 1);
  99358. vertices.push(-1, -1);
  99359. vertices.push(1, -1);
  99360. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99361. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99362. this._createIndexBuffer();
  99363. // Effects
  99364. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99365. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99366. }
  99367. Object.defineProperty(Layer.prototype, "onDispose", {
  99368. set: function (callback) {
  99369. if (this._onDisposeObserver) {
  99370. this.onDisposeObservable.remove(this._onDisposeObserver);
  99371. }
  99372. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99373. },
  99374. enumerable: true,
  99375. configurable: true
  99376. });
  99377. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99378. set: function (callback) {
  99379. if (this._onBeforeRenderObserver) {
  99380. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99381. }
  99382. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99383. },
  99384. enumerable: true,
  99385. configurable: true
  99386. });
  99387. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99388. set: function (callback) {
  99389. if (this._onAfterRenderObserver) {
  99390. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99391. }
  99392. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99393. },
  99394. enumerable: true,
  99395. configurable: true
  99396. });
  99397. Layer.prototype._createIndexBuffer = function () {
  99398. var engine = this._scene.getEngine();
  99399. // Indices
  99400. var indices = [];
  99401. indices.push(0);
  99402. indices.push(1);
  99403. indices.push(2);
  99404. indices.push(0);
  99405. indices.push(2);
  99406. indices.push(3);
  99407. this._indexBuffer = engine.createIndexBuffer(indices);
  99408. };
  99409. Layer.prototype._rebuild = function () {
  99410. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99411. if (vb) {
  99412. vb._rebuild();
  99413. }
  99414. this._createIndexBuffer();
  99415. };
  99416. Layer.prototype.render = function () {
  99417. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99418. // Check
  99419. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99420. return;
  99421. var engine = this._scene.getEngine();
  99422. this.onBeforeRenderObservable.notifyObservers(this);
  99423. // Render
  99424. engine.enableEffect(currentEffect);
  99425. engine.setState(false);
  99426. // Texture
  99427. currentEffect.setTexture("textureSampler", this.texture);
  99428. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99429. // Color
  99430. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99431. // Scale / offset
  99432. currentEffect.setVector2("offset", this.offset);
  99433. currentEffect.setVector2("scale", this.scale);
  99434. // VBOs
  99435. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99436. // Draw order
  99437. if (!this.alphaTest) {
  99438. engine.setAlphaMode(this.alphaBlendingMode);
  99439. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99441. }
  99442. else {
  99443. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99444. }
  99445. this.onAfterRenderObservable.notifyObservers(this);
  99446. };
  99447. Layer.prototype.dispose = function () {
  99448. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99449. if (vertexBuffer) {
  99450. vertexBuffer.dispose();
  99451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99452. }
  99453. if (this._indexBuffer) {
  99454. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99455. this._indexBuffer = null;
  99456. }
  99457. if (this.texture) {
  99458. this.texture.dispose();
  99459. this.texture = null;
  99460. }
  99461. // Remove from scene
  99462. var index = this._scene.layers.indexOf(this);
  99463. this._scene.layers.splice(index, 1);
  99464. // Callback
  99465. this.onDisposeObservable.notifyObservers(this);
  99466. this.onDisposeObservable.clear();
  99467. this.onAfterRenderObservable.clear();
  99468. this.onBeforeRenderObservable.clear();
  99469. };
  99470. return Layer;
  99471. }());
  99472. BABYLON.Layer = Layer;
  99473. })(BABYLON || (BABYLON = {}));
  99474. //# sourceMappingURL=babylon.layer.js.map
  99475. var BABYLON;
  99476. (function (BABYLON) {
  99477. var TextureTools = /** @class */ (function () {
  99478. function TextureTools() {
  99479. }
  99480. /**
  99481. * Uses the GPU to create a copy texture rescaled at a given size
  99482. * @param texture Texture to copy from
  99483. * @param width Desired width
  99484. * @param height Desired height
  99485. * @return Generated texture
  99486. */
  99487. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99488. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99489. var scene = texture.getScene();
  99490. var engine = scene.getEngine();
  99491. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99492. rtt.wrapU = texture.wrapU;
  99493. rtt.wrapV = texture.wrapV;
  99494. rtt.uOffset = texture.uOffset;
  99495. rtt.vOffset = texture.vOffset;
  99496. rtt.uScale = texture.uScale;
  99497. rtt.vScale = texture.vScale;
  99498. rtt.uAng = texture.uAng;
  99499. rtt.vAng = texture.vAng;
  99500. rtt.wAng = texture.wAng;
  99501. rtt.coordinatesIndex = texture.coordinatesIndex;
  99502. rtt.level = texture.level;
  99503. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99504. rtt._texture.isReady = false;
  99505. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99506. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99507. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99508. passPostProcess.getEffect().executeWhenCompiled(function () {
  99509. passPostProcess.onApply = function (effect) {
  99510. effect.setTexture("textureSampler", texture);
  99511. };
  99512. var internalTexture = rtt.getInternalTexture();
  99513. if (internalTexture) {
  99514. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99515. engine.unBindFramebuffer(internalTexture);
  99516. rtt.disposeFramebufferObjects();
  99517. passPostProcess.dispose();
  99518. internalTexture.isReady = true;
  99519. }
  99520. });
  99521. return rtt;
  99522. };
  99523. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99524. if (!scene._environmentBRDFTexture) {
  99525. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99526. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99527. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99528. scene._environmentBRDFTexture = texture;
  99529. }
  99530. return scene._environmentBRDFTexture;
  99531. };
  99532. 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=";
  99533. return TextureTools;
  99534. }());
  99535. BABYLON.TextureTools = TextureTools;
  99536. })(BABYLON || (BABYLON = {}));
  99537. //# sourceMappingURL=babylon.textureTools.js.map
  99538. var BABYLON;
  99539. (function (BABYLON) {
  99540. var FramingBehavior = /** @class */ (function () {
  99541. function FramingBehavior() {
  99542. this._mode = FramingBehavior.FitFrustumSidesMode;
  99543. this._radiusScale = 1.0;
  99544. this._positionScale = 0.5;
  99545. this._defaultElevation = 0.3;
  99546. this._elevationReturnTime = 1500;
  99547. this._elevationReturnWaitTime = 1000;
  99548. this._zoomStopsAnimation = false;
  99549. this._framingTime = 1500;
  99550. this._isPointerDown = false;
  99551. this._lastInteractionTime = -Infinity;
  99552. // Framing control
  99553. this._animatables = new Array();
  99554. this._betaIsAnimating = false;
  99555. }
  99556. Object.defineProperty(FramingBehavior.prototype, "name", {
  99557. get: function () {
  99558. return "Framing";
  99559. },
  99560. enumerable: true,
  99561. configurable: true
  99562. });
  99563. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99564. /**
  99565. * Gets current mode used by the behavior.
  99566. */
  99567. get: function () {
  99568. return this._mode;
  99569. },
  99570. /**
  99571. * Sets the current mode used by the behavior
  99572. */
  99573. set: function (mode) {
  99574. this._mode = mode;
  99575. },
  99576. enumerable: true,
  99577. configurable: true
  99578. });
  99579. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99580. /**
  99581. * Gets the scale applied to the radius
  99582. */
  99583. get: function () {
  99584. return this._radiusScale;
  99585. },
  99586. /**
  99587. * Sets the scale applied to the radius (1 by default)
  99588. */
  99589. set: function (radius) {
  99590. this._radiusScale = radius;
  99591. },
  99592. enumerable: true,
  99593. configurable: true
  99594. });
  99595. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99596. /**
  99597. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99598. */
  99599. get: function () {
  99600. return this._positionScale;
  99601. },
  99602. /**
  99603. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99604. */
  99605. set: function (scale) {
  99606. this._positionScale = scale;
  99607. },
  99608. enumerable: true,
  99609. configurable: true
  99610. });
  99611. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99612. /**
  99613. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99614. * behaviour is triggered, in radians.
  99615. */
  99616. get: function () {
  99617. return this._defaultElevation;
  99618. },
  99619. /**
  99620. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99621. * behaviour is triggered, in radians.
  99622. */
  99623. set: function (elevation) {
  99624. this._defaultElevation = elevation;
  99625. },
  99626. enumerable: true,
  99627. configurable: true
  99628. });
  99629. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99630. /**
  99631. * Gets the time (in milliseconds) taken to return to the default beta position.
  99632. * Negative value indicates camera should not return to default.
  99633. */
  99634. get: function () {
  99635. return this._elevationReturnTime;
  99636. },
  99637. /**
  99638. * Sets the time (in milliseconds) taken to return to the default beta position.
  99639. * Negative value indicates camera should not return to default.
  99640. */
  99641. set: function (speed) {
  99642. this._elevationReturnTime = speed;
  99643. },
  99644. enumerable: true,
  99645. configurable: true
  99646. });
  99647. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99648. /**
  99649. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99650. */
  99651. get: function () {
  99652. return this._elevationReturnWaitTime;
  99653. },
  99654. /**
  99655. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99656. */
  99657. set: function (time) {
  99658. this._elevationReturnWaitTime = time;
  99659. },
  99660. enumerable: true,
  99661. configurable: true
  99662. });
  99663. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99664. /**
  99665. * Gets the flag that indicates if user zooming should stop animation.
  99666. */
  99667. get: function () {
  99668. return this._zoomStopsAnimation;
  99669. },
  99670. /**
  99671. * Sets the flag that indicates if user zooming should stop animation.
  99672. */
  99673. set: function (flag) {
  99674. this._zoomStopsAnimation = flag;
  99675. },
  99676. enumerable: true,
  99677. configurable: true
  99678. });
  99679. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99680. /**
  99681. * Gets the transition time when framing the mesh, in milliseconds
  99682. */
  99683. get: function () {
  99684. return this._framingTime;
  99685. },
  99686. /**
  99687. * Sets the transition time when framing the mesh, in milliseconds
  99688. */
  99689. set: function (time) {
  99690. this._framingTime = time;
  99691. },
  99692. enumerable: true,
  99693. configurable: true
  99694. });
  99695. FramingBehavior.prototype.init = function () {
  99696. // Do notihng
  99697. };
  99698. FramingBehavior.prototype.attach = function (camera) {
  99699. var _this = this;
  99700. this._attachedCamera = camera;
  99701. var scene = this._attachedCamera.getScene();
  99702. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99703. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99704. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99705. _this._isPointerDown = true;
  99706. return;
  99707. }
  99708. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99709. _this._isPointerDown = false;
  99710. }
  99711. });
  99712. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99713. if (mesh) {
  99714. _this.zoomOnMesh(mesh);
  99715. }
  99716. });
  99717. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99718. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99719. _this._applyUserInteraction();
  99720. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99721. // back to the default position after a given timeout
  99722. _this._maintainCameraAboveGround();
  99723. });
  99724. };
  99725. FramingBehavior.prototype.detach = function () {
  99726. if (!this._attachedCamera) {
  99727. return;
  99728. }
  99729. var scene = this._attachedCamera.getScene();
  99730. if (this._onPrePointerObservableObserver) {
  99731. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99732. }
  99733. if (this._onAfterCheckInputsObserver) {
  99734. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99735. }
  99736. if (this._onMeshTargetChangedObserver) {
  99737. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99738. }
  99739. this._attachedCamera = null;
  99740. };
  99741. /**
  99742. * Targets the given mesh and updates zoom level accordingly.
  99743. * @param mesh The mesh to target.
  99744. * @param radius Optional. If a cached radius position already exists, overrides default.
  99745. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99746. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99747. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99748. */
  99749. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99750. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99751. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99752. mesh.computeWorldMatrix(true);
  99753. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99754. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99755. };
  99756. /**
  99757. * Targets the given mesh with its children and updates zoom level accordingly.
  99758. * @param mesh The mesh to target.
  99759. * @param radius Optional. If a cached radius position already exists, overrides default.
  99760. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99761. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99762. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99763. */
  99764. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99765. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99766. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99767. mesh.computeWorldMatrix(true);
  99768. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99769. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99770. };
  99771. /**
  99772. * Targets the given meshes with their children and updates zoom level accordingly.
  99773. * @param meshes The mesh to target.
  99774. * @param radius Optional. If a cached radius position already exists, overrides default.
  99775. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99776. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99777. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99778. */
  99779. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99780. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99781. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99782. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99783. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99784. for (var i = 0; i < meshes.length; i++) {
  99785. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99786. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99787. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99788. }
  99789. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99790. };
  99791. /**
  99792. * Targets the given mesh and updates zoom level accordingly.
  99793. * @param mesh The mesh to target.
  99794. * @param radius Optional. If a cached radius position already exists, overrides default.
  99795. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99796. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99797. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99798. */
  99799. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99800. var _this = this;
  99801. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99802. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99803. var zoomTarget;
  99804. if (!this._attachedCamera) {
  99805. return;
  99806. }
  99807. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99808. var bottom = minimumWorld.y;
  99809. var top = maximumWorld.y;
  99810. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99811. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99812. if (focusOnOriginXZ) {
  99813. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99814. }
  99815. else {
  99816. var centerWorld = minimumWorld.add(radiusWorld);
  99817. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99818. }
  99819. if (!this._vectorTransition) {
  99820. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99821. }
  99822. this._betaIsAnimating = true;
  99823. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99824. if (animatable) {
  99825. this._animatables.push(animatable);
  99826. }
  99827. // sets the radius and lower radius bounds
  99828. // Small delta ensures camera is not always at lower zoom limit.
  99829. var radius = 0;
  99830. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99831. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99832. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99833. radius = position;
  99834. }
  99835. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99836. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99837. if (this._attachedCamera.lowerRadiusLimit === null) {
  99838. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99839. }
  99840. }
  99841. // Set sensibilities
  99842. var extend = maximumWorld.subtract(minimumWorld).length();
  99843. this._attachedCamera.panningSensibility = 5000 / extend;
  99844. this._attachedCamera.wheelPrecision = 100 / radius;
  99845. // transition to new radius
  99846. if (!this._radiusTransition) {
  99847. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99848. }
  99849. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99850. _this.stopAllAnimations();
  99851. if (onAnimationEnd) {
  99852. onAnimationEnd();
  99853. }
  99854. if (_this._attachedCamera) {
  99855. _this._attachedCamera.storeState();
  99856. }
  99857. });
  99858. if (animatable) {
  99859. this._animatables.push(animatable);
  99860. }
  99861. };
  99862. /**
  99863. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99864. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99865. * frustum width.
  99866. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99867. * to fully enclose the mesh in the viewing frustum.
  99868. */
  99869. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99870. var size = maximumWorld.subtract(minimumWorld);
  99871. var boxVectorGlobalDiagonal = size.length();
  99872. var frustumSlope = this._getFrustumSlope();
  99873. // Formula for setting distance
  99874. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99875. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99876. // Horizon distance
  99877. var radius = radiusWithoutFraming * this._radiusScale;
  99878. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99879. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99880. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99881. var camera = this._attachedCamera;
  99882. if (!camera) {
  99883. return 0;
  99884. }
  99885. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99886. // Don't exceed the requested limit
  99887. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99888. }
  99889. // Don't exceed the upper radius limit
  99890. if (camera.upperRadiusLimit) {
  99891. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99892. }
  99893. return distance;
  99894. };
  99895. /**
  99896. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99897. * is automatically returned to its default position (expected to be above ground plane).
  99898. */
  99899. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99900. var _this = this;
  99901. if (this._elevationReturnTime < 0) {
  99902. return;
  99903. }
  99904. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99905. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99906. var limitBeta = Math.PI * 0.5;
  99907. // Bring the camera back up if below the ground plane
  99908. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99909. this._betaIsAnimating = true;
  99910. //Transition to new position
  99911. this.stopAllAnimations();
  99912. if (!this._betaTransition) {
  99913. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99914. }
  99915. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99916. _this._clearAnimationLocks();
  99917. _this.stopAllAnimations();
  99918. });
  99919. if (animatabe) {
  99920. this._animatables.push(animatabe);
  99921. }
  99922. }
  99923. };
  99924. /**
  99925. * Returns the frustum slope based on the canvas ratio and camera FOV
  99926. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99927. */
  99928. FramingBehavior.prototype._getFrustumSlope = function () {
  99929. // Calculate the viewport ratio
  99930. // Aspect Ratio is Height/Width.
  99931. var camera = this._attachedCamera;
  99932. if (!camera) {
  99933. return BABYLON.Vector2.Zero();
  99934. }
  99935. var engine = camera.getScene().getEngine();
  99936. var aspectRatio = engine.getAspectRatio(camera);
  99937. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99938. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99939. var frustumSlopeY = Math.tan(camera.fov / 2);
  99940. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99941. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99942. // along the forward vector.
  99943. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99944. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99945. };
  99946. /**
  99947. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99948. */
  99949. FramingBehavior.prototype._clearAnimationLocks = function () {
  99950. this._betaIsAnimating = false;
  99951. };
  99952. /**
  99953. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99954. */
  99955. FramingBehavior.prototype._applyUserInteraction = function () {
  99956. if (this.isUserIsMoving) {
  99957. this._lastInteractionTime = BABYLON.Tools.Now;
  99958. this.stopAllAnimations();
  99959. this._clearAnimationLocks();
  99960. }
  99961. };
  99962. /**
  99963. * Stops and removes all animations that have been applied to the camera
  99964. */
  99965. FramingBehavior.prototype.stopAllAnimations = function () {
  99966. if (this._attachedCamera) {
  99967. this._attachedCamera.animations = [];
  99968. }
  99969. while (this._animatables.length) {
  99970. if (this._animatables[0]) {
  99971. this._animatables[0].onAnimationEnd = null;
  99972. this._animatables[0].stop();
  99973. }
  99974. this._animatables.shift();
  99975. }
  99976. };
  99977. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99978. /**
  99979. * Gets a value indicating if the user is moving the camera
  99980. */
  99981. get: function () {
  99982. if (!this._attachedCamera) {
  99983. return false;
  99984. }
  99985. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99986. this._attachedCamera.inertialBetaOffset !== 0 ||
  99987. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99988. this._attachedCamera.inertialPanningX !== 0 ||
  99989. this._attachedCamera.inertialPanningY !== 0 ||
  99990. this._isPointerDown;
  99991. },
  99992. enumerable: true,
  99993. configurable: true
  99994. });
  99995. /**
  99996. * The easing function used by animations
  99997. */
  99998. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99999. /**
  100000. * The easing mode used by animations
  100001. */
  100002. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100003. // Statics
  100004. /**
  100005. * The camera can move all the way towards the mesh.
  100006. */
  100007. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100008. /**
  100009. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100010. */
  100011. FramingBehavior.FitFrustumSidesMode = 1;
  100012. return FramingBehavior;
  100013. }());
  100014. BABYLON.FramingBehavior = FramingBehavior;
  100015. })(BABYLON || (BABYLON = {}));
  100016. //# sourceMappingURL=babylon.framingBehavior.js.map
  100017. var BABYLON;
  100018. (function (BABYLON) {
  100019. /**
  100020. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100021. */
  100022. var BouncingBehavior = /** @class */ (function () {
  100023. function BouncingBehavior() {
  100024. /**
  100025. * The duration of the animation, in milliseconds
  100026. */
  100027. this.transitionDuration = 450;
  100028. /**
  100029. * Length of the distance animated by the transition when lower radius is reached
  100030. */
  100031. this.lowerRadiusTransitionRange = 2;
  100032. /**
  100033. * Length of the distance animated by the transition when upper radius is reached
  100034. */
  100035. this.upperRadiusTransitionRange = -2;
  100036. this._autoTransitionRange = false;
  100037. // Animations
  100038. this._radiusIsAnimating = false;
  100039. this._radiusBounceTransition = null;
  100040. this._animatables = new Array();
  100041. }
  100042. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100043. get: function () {
  100044. return "Bouncing";
  100045. },
  100046. enumerable: true,
  100047. configurable: true
  100048. });
  100049. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100050. /**
  100051. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100052. */
  100053. get: function () {
  100054. return this._autoTransitionRange;
  100055. },
  100056. /**
  100057. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100058. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100059. */
  100060. set: function (value) {
  100061. var _this = this;
  100062. if (this._autoTransitionRange === value) {
  100063. return;
  100064. }
  100065. this._autoTransitionRange = value;
  100066. var camera = this._attachedCamera;
  100067. if (!camera) {
  100068. return;
  100069. }
  100070. if (value) {
  100071. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100072. if (!mesh) {
  100073. return;
  100074. }
  100075. mesh.computeWorldMatrix(true);
  100076. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100077. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100078. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100079. });
  100080. }
  100081. else if (this._onMeshTargetChangedObserver) {
  100082. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100083. }
  100084. },
  100085. enumerable: true,
  100086. configurable: true
  100087. });
  100088. BouncingBehavior.prototype.init = function () {
  100089. // Do notihng
  100090. };
  100091. BouncingBehavior.prototype.attach = function (camera) {
  100092. var _this = this;
  100093. this._attachedCamera = camera;
  100094. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100095. if (!_this._attachedCamera) {
  100096. return;
  100097. }
  100098. // Add the bounce animation to the lower radius limit
  100099. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100100. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100101. }
  100102. // Add the bounce animation to the upper radius limit
  100103. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100104. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100105. }
  100106. });
  100107. };
  100108. BouncingBehavior.prototype.detach = function () {
  100109. if (!this._attachedCamera) {
  100110. return;
  100111. }
  100112. if (this._onAfterCheckInputsObserver) {
  100113. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100114. }
  100115. if (this._onMeshTargetChangedObserver) {
  100116. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100117. }
  100118. this._attachedCamera = null;
  100119. };
  100120. /**
  100121. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100122. * @param radiusLimit The limit to check against.
  100123. * @return Bool to indicate if at limit.
  100124. */
  100125. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100126. if (!this._attachedCamera) {
  100127. return false;
  100128. }
  100129. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100130. return true;
  100131. }
  100132. return false;
  100133. };
  100134. /**
  100135. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100136. * @param radiusDelta The delta by which to animate to. Can be negative.
  100137. */
  100138. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100139. var _this = this;
  100140. if (!this._attachedCamera) {
  100141. return;
  100142. }
  100143. if (!this._radiusBounceTransition) {
  100144. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100145. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100146. }
  100147. // Prevent zoom until bounce has completed
  100148. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100149. this._attachedCamera.wheelPrecision = Infinity;
  100150. this._attachedCamera.inertialRadiusOffset = 0;
  100151. // Animate to the radius limit
  100152. this.stopAllAnimations();
  100153. this._radiusIsAnimating = true;
  100154. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100155. if (animatable) {
  100156. this._animatables.push(animatable);
  100157. }
  100158. };
  100159. /**
  100160. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100161. */
  100162. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100163. this._radiusIsAnimating = false;
  100164. if (this._attachedCamera) {
  100165. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100166. }
  100167. };
  100168. /**
  100169. * Stops and removes all animations that have been applied to the camera
  100170. */
  100171. BouncingBehavior.prototype.stopAllAnimations = function () {
  100172. if (this._attachedCamera) {
  100173. this._attachedCamera.animations = [];
  100174. }
  100175. while (this._animatables.length) {
  100176. this._animatables[0].onAnimationEnd = null;
  100177. this._animatables[0].stop();
  100178. this._animatables.shift();
  100179. }
  100180. };
  100181. /**
  100182. * The easing function used by animations
  100183. */
  100184. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100185. /**
  100186. * The easing mode used by animations
  100187. */
  100188. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100189. return BouncingBehavior;
  100190. }());
  100191. BABYLON.BouncingBehavior = BouncingBehavior;
  100192. })(BABYLON || (BABYLON = {}));
  100193. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100194. var BABYLON;
  100195. (function (BABYLON) {
  100196. var AutoRotationBehavior = /** @class */ (function () {
  100197. function AutoRotationBehavior() {
  100198. this._zoomStopsAnimation = false;
  100199. this._idleRotationSpeed = 0.05;
  100200. this._idleRotationWaitTime = 2000;
  100201. this._idleRotationSpinupTime = 2000;
  100202. this._isPointerDown = false;
  100203. this._lastFrameTime = null;
  100204. this._lastInteractionTime = -Infinity;
  100205. this._cameraRotationSpeed = 0;
  100206. this._lastFrameRadius = 0;
  100207. }
  100208. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100209. get: function () {
  100210. return "AutoRotation";
  100211. },
  100212. enumerable: true,
  100213. configurable: true
  100214. });
  100215. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100216. /**
  100217. * Gets the flag that indicates if user zooming should stop animation.
  100218. */
  100219. get: function () {
  100220. return this._zoomStopsAnimation;
  100221. },
  100222. /**
  100223. * Sets the flag that indicates if user zooming should stop animation.
  100224. */
  100225. set: function (flag) {
  100226. this._zoomStopsAnimation = flag;
  100227. },
  100228. enumerable: true,
  100229. configurable: true
  100230. });
  100231. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100232. /**
  100233. * Gets the default speed at which the camera rotates around the model.
  100234. */
  100235. get: function () {
  100236. return this._idleRotationSpeed;
  100237. },
  100238. /**
  100239. * Sets the default speed at which the camera rotates around the model.
  100240. */
  100241. set: function (speed) {
  100242. this._idleRotationSpeed = speed;
  100243. },
  100244. enumerable: true,
  100245. configurable: true
  100246. });
  100247. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100248. /**
  100249. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100250. */
  100251. get: function () {
  100252. return this._idleRotationWaitTime;
  100253. },
  100254. /**
  100255. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100256. */
  100257. set: function (time) {
  100258. this._idleRotationWaitTime = time;
  100259. },
  100260. enumerable: true,
  100261. configurable: true
  100262. });
  100263. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100264. /**
  100265. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100266. */
  100267. get: function () {
  100268. return this._idleRotationSpinupTime;
  100269. },
  100270. /**
  100271. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100272. */
  100273. set: function (time) {
  100274. this._idleRotationSpinupTime = time;
  100275. },
  100276. enumerable: true,
  100277. configurable: true
  100278. });
  100279. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100280. /**
  100281. * Gets a value indicating if the camera is currently rotating because of this behavior
  100282. */
  100283. get: function () {
  100284. return Math.abs(this._cameraRotationSpeed) > 0;
  100285. },
  100286. enumerable: true,
  100287. configurable: true
  100288. });
  100289. AutoRotationBehavior.prototype.init = function () {
  100290. // Do notihng
  100291. };
  100292. AutoRotationBehavior.prototype.attach = function (camera) {
  100293. var _this = this;
  100294. this._attachedCamera = camera;
  100295. var scene = this._attachedCamera.getScene();
  100296. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100297. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100298. _this._isPointerDown = true;
  100299. return;
  100300. }
  100301. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100302. _this._isPointerDown = false;
  100303. }
  100304. });
  100305. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100306. var now = BABYLON.Tools.Now;
  100307. var dt = 0;
  100308. if (_this._lastFrameTime != null) {
  100309. dt = now - _this._lastFrameTime;
  100310. }
  100311. _this._lastFrameTime = now;
  100312. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100313. _this._applyUserInteraction();
  100314. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100315. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100316. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100317. // Step camera rotation by rotation speed
  100318. if (_this._attachedCamera) {
  100319. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100320. }
  100321. });
  100322. };
  100323. AutoRotationBehavior.prototype.detach = function () {
  100324. if (!this._attachedCamera) {
  100325. return;
  100326. }
  100327. var scene = this._attachedCamera.getScene();
  100328. if (this._onPrePointerObservableObserver) {
  100329. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100330. }
  100331. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100332. this._attachedCamera = null;
  100333. };
  100334. /**
  100335. * Returns true if user is scrolling.
  100336. * @return true if user is scrolling.
  100337. */
  100338. AutoRotationBehavior.prototype._userIsZooming = function () {
  100339. if (!this._attachedCamera) {
  100340. return false;
  100341. }
  100342. return this._attachedCamera.inertialRadiusOffset !== 0;
  100343. };
  100344. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100345. if (!this._attachedCamera) {
  100346. return false;
  100347. }
  100348. var zoomHasHitLimit = false;
  100349. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100350. zoomHasHitLimit = true;
  100351. }
  100352. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100353. this._lastFrameRadius = this._attachedCamera.radius;
  100354. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100355. };
  100356. /**
  100357. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100358. */
  100359. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100360. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100361. this._lastInteractionTime = BABYLON.Tools.Now;
  100362. }
  100363. };
  100364. // Tools
  100365. AutoRotationBehavior.prototype._userIsMoving = function () {
  100366. if (!this._attachedCamera) {
  100367. return false;
  100368. }
  100369. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100370. this._attachedCamera.inertialBetaOffset !== 0 ||
  100371. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100372. this._attachedCamera.inertialPanningX !== 0 ||
  100373. this._attachedCamera.inertialPanningY !== 0 ||
  100374. this._isPointerDown;
  100375. };
  100376. return AutoRotationBehavior;
  100377. }());
  100378. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100379. })(BABYLON || (BABYLON = {}));
  100380. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100381. var BABYLON;
  100382. (function (BABYLON) {
  100383. var NullEngineOptions = /** @class */ (function () {
  100384. function NullEngineOptions() {
  100385. this.renderWidth = 512;
  100386. this.renderHeight = 256;
  100387. this.textureSize = 512;
  100388. this.deterministicLockstep = false;
  100389. this.lockstepMaxSteps = 4;
  100390. }
  100391. return NullEngineOptions;
  100392. }());
  100393. BABYLON.NullEngineOptions = NullEngineOptions;
  100394. /**
  100395. * The null engine class provides support for headless version of babylon.js.
  100396. * This can be used in server side scenario or for testing purposes
  100397. */
  100398. var NullEngine = /** @class */ (function (_super) {
  100399. __extends(NullEngine, _super);
  100400. function NullEngine(options) {
  100401. if (options === void 0) { options = new NullEngineOptions(); }
  100402. var _this = _super.call(this, null) || this;
  100403. if (options.deterministicLockstep === undefined) {
  100404. options.deterministicLockstep = false;
  100405. }
  100406. if (options.lockstepMaxSteps === undefined) {
  100407. options.lockstepMaxSteps = 4;
  100408. }
  100409. _this._options = options;
  100410. // Init caps
  100411. // We consider we are on a webgl1 capable device
  100412. _this._caps = new BABYLON.EngineCapabilities();
  100413. _this._caps.maxTexturesImageUnits = 16;
  100414. _this._caps.maxVertexTextureImageUnits = 16;
  100415. _this._caps.maxTextureSize = 512;
  100416. _this._caps.maxCubemapTextureSize = 512;
  100417. _this._caps.maxRenderTextureSize = 512;
  100418. _this._caps.maxVertexAttribs = 16;
  100419. _this._caps.maxVaryingVectors = 16;
  100420. _this._caps.maxFragmentUniformVectors = 16;
  100421. _this._caps.maxVertexUniformVectors = 16;
  100422. // Extensions
  100423. _this._caps.standardDerivatives = false;
  100424. _this._caps.astc = null;
  100425. _this._caps.s3tc = null;
  100426. _this._caps.pvrtc = null;
  100427. _this._caps.etc1 = null;
  100428. _this._caps.etc2 = null;
  100429. _this._caps.textureAnisotropicFilterExtension = null;
  100430. _this._caps.maxAnisotropy = 0;
  100431. _this._caps.uintIndices = false;
  100432. _this._caps.fragmentDepthSupported = false;
  100433. _this._caps.highPrecisionShaderSupported = true;
  100434. _this._caps.colorBufferFloat = false;
  100435. _this._caps.textureFloat = false;
  100436. _this._caps.textureFloatLinearFiltering = false;
  100437. _this._caps.textureFloatRender = false;
  100438. _this._caps.textureHalfFloat = false;
  100439. _this._caps.textureHalfFloatLinearFiltering = false;
  100440. _this._caps.textureHalfFloatRender = false;
  100441. _this._caps.textureLOD = false;
  100442. _this._caps.drawBuffersExtension = false;
  100443. _this._caps.depthTextureExtension = false;
  100444. _this._caps.vertexArrayObject = false;
  100445. _this._caps.instancedArrays = false;
  100446. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100447. // Wrappers
  100448. if (typeof URL === "undefined") {
  100449. URL = {
  100450. createObjectURL: function () { },
  100451. revokeObjectURL: function () { }
  100452. };
  100453. }
  100454. if (typeof Blob === "undefined") {
  100455. Blob = function () { };
  100456. }
  100457. return _this;
  100458. }
  100459. NullEngine.prototype.isDeterministicLockStep = function () {
  100460. return this._options.deterministicLockstep;
  100461. };
  100462. NullEngine.prototype.getLockstepMaxSteps = function () {
  100463. return this._options.lockstepMaxSteps;
  100464. };
  100465. NullEngine.prototype.getHardwareScalingLevel = function () {
  100466. return 1.0;
  100467. };
  100468. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100469. return {
  100470. capacity: 0,
  100471. references: 1,
  100472. is32Bits: false
  100473. };
  100474. };
  100475. NullEngine.prototype.createIndexBuffer = function (indices) {
  100476. return {
  100477. capacity: 0,
  100478. references: 1,
  100479. is32Bits: false
  100480. };
  100481. };
  100482. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100483. if (stencil === void 0) { stencil = false; }
  100484. };
  100485. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100486. if (useScreen === void 0) { useScreen = false; }
  100487. if (!useScreen && this._currentRenderTarget) {
  100488. return this._currentRenderTarget.width;
  100489. }
  100490. return this._options.renderWidth;
  100491. };
  100492. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100493. if (useScreen === void 0) { useScreen = false; }
  100494. if (!useScreen && this._currentRenderTarget) {
  100495. return this._currentRenderTarget.height;
  100496. }
  100497. return this._options.renderHeight;
  100498. };
  100499. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100500. this._cachedViewport = viewport;
  100501. };
  100502. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100503. return {
  100504. transformFeedback: null,
  100505. __SPECTOR_rebuildProgram: null
  100506. };
  100507. };
  100508. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100509. return [];
  100510. };
  100511. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100512. return [];
  100513. };
  100514. NullEngine.prototype.bindSamplers = function (effect) {
  100515. this._currentEffect = null;
  100516. };
  100517. NullEngine.prototype.enableEffect = function (effect) {
  100518. this._currentEffect = effect;
  100519. if (effect.onBind) {
  100520. effect.onBind(effect);
  100521. }
  100522. effect.onBindObservable.notifyObservers(effect);
  100523. };
  100524. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100525. if (zOffset === void 0) { zOffset = 0; }
  100526. if (reverseSide === void 0) { reverseSide = false; }
  100527. };
  100528. NullEngine.prototype.setIntArray = function (uniform, array) {
  100529. };
  100530. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100531. };
  100532. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100533. };
  100534. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100535. };
  100536. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100537. };
  100538. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100539. };
  100540. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100541. };
  100542. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100543. };
  100544. NullEngine.prototype.setArray = function (uniform, array) {
  100545. };
  100546. NullEngine.prototype.setArray2 = function (uniform, array) {
  100547. };
  100548. NullEngine.prototype.setArray3 = function (uniform, array) {
  100549. };
  100550. NullEngine.prototype.setArray4 = function (uniform, array) {
  100551. };
  100552. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100553. };
  100554. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100555. };
  100556. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100557. };
  100558. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100559. };
  100560. NullEngine.prototype.setFloat = function (uniform, value) {
  100561. };
  100562. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100563. };
  100564. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100565. };
  100566. NullEngine.prototype.setBool = function (uniform, bool) {
  100567. };
  100568. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100569. };
  100570. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100571. };
  100572. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100573. };
  100574. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100575. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100576. if (this._alphaMode === mode) {
  100577. return;
  100578. }
  100579. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100580. if (!noDepthWriteChange) {
  100581. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100582. }
  100583. this._alphaMode = mode;
  100584. };
  100585. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100586. };
  100587. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100588. if (this.preventCacheWipeBetweenFrames) {
  100589. return;
  100590. }
  100591. this.resetTextureCache();
  100592. this._currentEffect = null;
  100593. if (bruteForce) {
  100594. this._currentProgram = null;
  100595. this._stencilState.reset();
  100596. this._depthCullingState.reset();
  100597. this._alphaState.reset();
  100598. }
  100599. this._cachedVertexBuffers = null;
  100600. this._cachedIndexBuffer = null;
  100601. this._cachedEffectForVertexBuffers = null;
  100602. };
  100603. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100604. };
  100605. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100606. };
  100607. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100608. };
  100609. NullEngine.prototype._createTexture = function () {
  100610. return {};
  100611. };
  100612. NullEngine.prototype._releaseTexture = function (texture) {
  100613. };
  100614. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100616. if (onLoad === void 0) { onLoad = null; }
  100617. if (onError === void 0) { onError = null; }
  100618. if (buffer === void 0) { buffer = null; }
  100619. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100620. var url = String(urlArg);
  100621. texture.url = url;
  100622. texture.generateMipMaps = !noMipmap;
  100623. texture.samplingMode = samplingMode;
  100624. texture.invertY = invertY;
  100625. texture.baseWidth = this._options.textureSize;
  100626. texture.baseHeight = this._options.textureSize;
  100627. texture.width = this._options.textureSize;
  100628. texture.height = this._options.textureSize;
  100629. if (format) {
  100630. texture.format = format;
  100631. }
  100632. texture.isReady = true;
  100633. if (onLoad) {
  100634. onLoad();
  100635. }
  100636. this._internalTexturesCache.push(texture);
  100637. return texture;
  100638. };
  100639. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100640. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100641. if (options !== undefined && typeof options === "object") {
  100642. fullOptions.generateMipMaps = options.generateMipMaps;
  100643. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100644. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100645. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100646. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100647. }
  100648. else {
  100649. fullOptions.generateMipMaps = options;
  100650. fullOptions.generateDepthBuffer = true;
  100651. fullOptions.generateStencilBuffer = false;
  100652. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100653. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100654. }
  100655. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100656. var width = size.width || size;
  100657. var height = size.height || size;
  100658. texture._depthStencilBuffer = {};
  100659. texture._framebuffer = {};
  100660. texture.baseWidth = width;
  100661. texture.baseHeight = height;
  100662. texture.width = width;
  100663. texture.height = height;
  100664. texture.isReady = true;
  100665. texture.samples = 1;
  100666. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100667. texture.samplingMode = fullOptions.samplingMode;
  100668. texture.type = fullOptions.type;
  100669. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100670. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100671. this._internalTexturesCache.push(texture);
  100672. return texture;
  100673. };
  100674. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100675. texture.samplingMode = samplingMode;
  100676. };
  100677. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100678. if (this._currentRenderTarget) {
  100679. this.unBindFramebuffer(this._currentRenderTarget);
  100680. }
  100681. this._currentRenderTarget = texture;
  100682. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100683. if (this._cachedViewport && !forceFullscreenViewport) {
  100684. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100685. }
  100686. };
  100687. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100688. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100689. this._currentRenderTarget = null;
  100690. if (onBeforeUnbind) {
  100691. if (texture._MSAAFramebuffer) {
  100692. this._currentFramebuffer = texture._framebuffer;
  100693. }
  100694. onBeforeUnbind();
  100695. }
  100696. this._currentFramebuffer = null;
  100697. };
  100698. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100699. var vbo = {
  100700. capacity: 1,
  100701. references: 1,
  100702. is32Bits: false
  100703. };
  100704. return vbo;
  100705. };
  100706. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100707. if (premulAlpha === void 0) { premulAlpha = false; }
  100708. };
  100709. /**
  100710. * Get the current error code of the webGL context
  100711. * @returns the error code
  100712. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  100713. */
  100714. NullEngine.prototype.getError = function () {
  100715. return 0;
  100716. };
  100717. /** @hidden */
  100718. NullEngine.prototype._getUnpackAlignement = function () {
  100719. return 1;
  100720. };
  100721. /** @hidden */
  100722. NullEngine.prototype._unpackFlipY = function (value) {
  100723. };
  100724. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100725. if (offset === void 0) { offset = 0; }
  100726. };
  100727. /**
  100728. * Updates a dynamic vertex buffer.
  100729. * @param vertexBuffer the vertex buffer to update
  100730. * @param data the data used to update the vertex buffer
  100731. * @param byteOffset the byte offset of the data (optional)
  100732. * @param byteLength the byte length of the data (optional)
  100733. */
  100734. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100735. };
  100736. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100737. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100738. this._boundTexturesCache[this._activeChannel] = texture;
  100739. return true;
  100740. }
  100741. return false;
  100742. };
  100743. NullEngine.prototype._bindTexture = function (channel, texture) {
  100744. if (channel < 0) {
  100745. return;
  100746. }
  100747. this._bindTextureDirectly(0, texture);
  100748. };
  100749. NullEngine.prototype._releaseBuffer = function (buffer) {
  100750. buffer.references--;
  100751. if (buffer.references === 0) {
  100752. return true;
  100753. }
  100754. return false;
  100755. };
  100756. NullEngine.prototype.releaseEffects = function () {
  100757. };
  100758. NullEngine.prototype.displayLoadingUI = function () {
  100759. };
  100760. NullEngine.prototype.hideLoadingUI = function () {
  100761. };
  100762. /** @hidden */
  100763. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  100764. if (faceIndex === void 0) { faceIndex = 0; }
  100765. if (lod === void 0) { lod = 0; }
  100766. };
  100767. /** @hidden */
  100768. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  100769. if (faceIndex === void 0) { faceIndex = 0; }
  100770. if (lod === void 0) { lod = 0; }
  100771. };
  100772. /** @hidden */
  100773. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  100774. if (faceIndex === void 0) { faceIndex = 0; }
  100775. if (lod === void 0) { lod = 0; }
  100776. };
  100777. /** @hidden */
  100778. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  100779. if (faceIndex === void 0) { faceIndex = 0; }
  100780. if (lod === void 0) { lod = 0; }
  100781. };
  100782. return NullEngine;
  100783. }(BABYLON.Engine));
  100784. BABYLON.NullEngine = NullEngine;
  100785. })(BABYLON || (BABYLON = {}));
  100786. //# sourceMappingURL=babylon.nullEngine.js.map
  100787. var BABYLON;
  100788. (function (BABYLON) {
  100789. /**
  100790. * This class can be used to get instrumentation data from a Babylon engine
  100791. */
  100792. var EngineInstrumentation = /** @class */ (function () {
  100793. function EngineInstrumentation(engine) {
  100794. this.engine = engine;
  100795. this._captureGPUFrameTime = false;
  100796. this._gpuFrameTime = new BABYLON.PerfCounter();
  100797. this._captureShaderCompilationTime = false;
  100798. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100799. // Observers
  100800. this._onBeginFrameObserver = null;
  100801. this._onEndFrameObserver = null;
  100802. this._onBeforeShaderCompilationObserver = null;
  100803. this._onAfterShaderCompilationObserver = null;
  100804. }
  100805. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100806. // Properties
  100807. /**
  100808. * Gets the perf counter used for GPU frame time
  100809. */
  100810. get: function () {
  100811. return this._gpuFrameTime;
  100812. },
  100813. enumerable: true,
  100814. configurable: true
  100815. });
  100816. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100817. /**
  100818. * Gets the GPU frame time capture status
  100819. */
  100820. get: function () {
  100821. return this._captureGPUFrameTime;
  100822. },
  100823. /**
  100824. * Enable or disable the GPU frame time capture
  100825. */
  100826. set: function (value) {
  100827. var _this = this;
  100828. if (value === this._captureGPUFrameTime) {
  100829. return;
  100830. }
  100831. this._captureGPUFrameTime = value;
  100832. if (value) {
  100833. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100834. if (!_this._gpuFrameTimeToken) {
  100835. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100836. }
  100837. });
  100838. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100839. if (!_this._gpuFrameTimeToken) {
  100840. return;
  100841. }
  100842. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100843. if (time > -1) {
  100844. _this._gpuFrameTimeToken = null;
  100845. _this._gpuFrameTime.fetchNewFrame();
  100846. _this._gpuFrameTime.addCount(time, true);
  100847. }
  100848. });
  100849. }
  100850. else {
  100851. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100852. this._onBeginFrameObserver = null;
  100853. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100854. this._onEndFrameObserver = null;
  100855. }
  100856. },
  100857. enumerable: true,
  100858. configurable: true
  100859. });
  100860. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100861. /**
  100862. * Gets the perf counter used for shader compilation time
  100863. */
  100864. get: function () {
  100865. return this._shaderCompilationTime;
  100866. },
  100867. enumerable: true,
  100868. configurable: true
  100869. });
  100870. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100871. /**
  100872. * Gets the shader compilation time capture status
  100873. */
  100874. get: function () {
  100875. return this._captureShaderCompilationTime;
  100876. },
  100877. /**
  100878. * Enable or disable the shader compilation time capture
  100879. */
  100880. set: function (value) {
  100881. var _this = this;
  100882. if (value === this._captureShaderCompilationTime) {
  100883. return;
  100884. }
  100885. this._captureShaderCompilationTime = value;
  100886. if (value) {
  100887. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100888. _this._shaderCompilationTime.fetchNewFrame();
  100889. _this._shaderCompilationTime.beginMonitoring();
  100890. });
  100891. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100892. _this._shaderCompilationTime.endMonitoring();
  100893. });
  100894. }
  100895. else {
  100896. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100897. this._onBeforeShaderCompilationObserver = null;
  100898. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100899. this._onAfterShaderCompilationObserver = null;
  100900. }
  100901. },
  100902. enumerable: true,
  100903. configurable: true
  100904. });
  100905. EngineInstrumentation.prototype.dispose = function () {
  100906. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100907. this._onBeginFrameObserver = null;
  100908. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100909. this._onEndFrameObserver = null;
  100910. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100911. this._onBeforeShaderCompilationObserver = null;
  100912. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100913. this._onAfterShaderCompilationObserver = null;
  100914. this.engine = null;
  100915. };
  100916. return EngineInstrumentation;
  100917. }());
  100918. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100919. })(BABYLON || (BABYLON = {}));
  100920. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100921. var BABYLON;
  100922. (function (BABYLON) {
  100923. /**
  100924. * This class can be used to get instrumentation data from a Babylon engine
  100925. */
  100926. var SceneInstrumentation = /** @class */ (function () {
  100927. function SceneInstrumentation(scene) {
  100928. var _this = this;
  100929. this.scene = scene;
  100930. this._captureActiveMeshesEvaluationTime = false;
  100931. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100932. this._captureRenderTargetsRenderTime = false;
  100933. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100934. this._captureFrameTime = false;
  100935. this._frameTime = new BABYLON.PerfCounter();
  100936. this._captureRenderTime = false;
  100937. this._renderTime = new BABYLON.PerfCounter();
  100938. this._captureInterFrameTime = false;
  100939. this._interFrameTime = new BABYLON.PerfCounter();
  100940. this._captureParticlesRenderTime = false;
  100941. this._particlesRenderTime = new BABYLON.PerfCounter();
  100942. this._captureSpritesRenderTime = false;
  100943. this._spritesRenderTime = new BABYLON.PerfCounter();
  100944. this._capturePhysicsTime = false;
  100945. this._physicsTime = new BABYLON.PerfCounter();
  100946. this._captureAnimationsTime = false;
  100947. this._animationsTime = new BABYLON.PerfCounter();
  100948. this._captureCameraRenderTime = false;
  100949. this._cameraRenderTime = new BABYLON.PerfCounter();
  100950. // Observers
  100951. this._onBeforeActiveMeshesEvaluationObserver = null;
  100952. this._onAfterActiveMeshesEvaluationObserver = null;
  100953. this._onBeforeRenderTargetsRenderObserver = null;
  100954. this._onAfterRenderTargetsRenderObserver = null;
  100955. this._onAfterRenderObserver = null;
  100956. this._onBeforeDrawPhaseObserver = null;
  100957. this._onAfterDrawPhaseObserver = null;
  100958. this._onBeforeAnimationsObserver = null;
  100959. this._onBeforeParticlesRenderingObserver = null;
  100960. this._onAfterParticlesRenderingObserver = null;
  100961. this._onBeforeSpritesRenderingObserver = null;
  100962. this._onAfterSpritesRenderingObserver = null;
  100963. this._onBeforePhysicsObserver = null;
  100964. this._onAfterPhysicsObserver = null;
  100965. this._onAfterAnimationsObserver = null;
  100966. this._onBeforeCameraRenderObserver = null;
  100967. this._onAfterCameraRenderObserver = null;
  100968. // Before render
  100969. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100970. if (_this._captureActiveMeshesEvaluationTime) {
  100971. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100972. }
  100973. if (_this._captureRenderTargetsRenderTime) {
  100974. _this._renderTargetsRenderTime.fetchNewFrame();
  100975. }
  100976. if (_this._captureFrameTime) {
  100977. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100978. _this._frameTime.beginMonitoring();
  100979. }
  100980. if (_this._captureInterFrameTime) {
  100981. _this._interFrameTime.endMonitoring();
  100982. }
  100983. if (_this._captureParticlesRenderTime) {
  100984. _this._particlesRenderTime.fetchNewFrame();
  100985. }
  100986. if (_this._captureSpritesRenderTime) {
  100987. _this._spritesRenderTime.fetchNewFrame();
  100988. }
  100989. if (_this._captureAnimationsTime) {
  100990. _this._animationsTime.beginMonitoring();
  100991. }
  100992. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100993. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100994. });
  100995. // After render
  100996. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100997. if (_this._captureFrameTime) {
  100998. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100999. _this._frameTime.endMonitoring();
  101000. }
  101001. if (_this._captureRenderTime) {
  101002. _this._renderTime.endMonitoring(false);
  101003. }
  101004. if (_this._captureInterFrameTime) {
  101005. _this._interFrameTime.beginMonitoring();
  101006. }
  101007. });
  101008. }
  101009. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101010. // Properties
  101011. /**
  101012. * Gets the perf counter used for active meshes evaluation time
  101013. */
  101014. get: function () {
  101015. return this._activeMeshesEvaluationTime;
  101016. },
  101017. enumerable: true,
  101018. configurable: true
  101019. });
  101020. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101021. /**
  101022. * Gets the active meshes evaluation time capture status
  101023. */
  101024. get: function () {
  101025. return this._captureActiveMeshesEvaluationTime;
  101026. },
  101027. /**
  101028. * Enable or disable the active meshes evaluation time capture
  101029. */
  101030. set: function (value) {
  101031. var _this = this;
  101032. if (value === this._captureActiveMeshesEvaluationTime) {
  101033. return;
  101034. }
  101035. this._captureActiveMeshesEvaluationTime = value;
  101036. if (value) {
  101037. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101038. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101039. _this._activeMeshesEvaluationTime.beginMonitoring();
  101040. });
  101041. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101042. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101043. _this._activeMeshesEvaluationTime.endMonitoring();
  101044. });
  101045. }
  101046. else {
  101047. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101048. this._onBeforeActiveMeshesEvaluationObserver = null;
  101049. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101050. this._onAfterActiveMeshesEvaluationObserver = null;
  101051. }
  101052. },
  101053. enumerable: true,
  101054. configurable: true
  101055. });
  101056. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101057. /**
  101058. * Gets the perf counter used for render targets render time
  101059. */
  101060. get: function () {
  101061. return this._renderTargetsRenderTime;
  101062. },
  101063. enumerable: true,
  101064. configurable: true
  101065. });
  101066. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101067. /**
  101068. * Gets the render targets render time capture status
  101069. */
  101070. get: function () {
  101071. return this._captureRenderTargetsRenderTime;
  101072. },
  101073. /**
  101074. * Enable or disable the render targets render time capture
  101075. */
  101076. set: function (value) {
  101077. var _this = this;
  101078. if (value === this._captureRenderTargetsRenderTime) {
  101079. return;
  101080. }
  101081. this._captureRenderTargetsRenderTime = value;
  101082. if (value) {
  101083. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101084. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101085. _this._renderTargetsRenderTime.beginMonitoring();
  101086. });
  101087. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101088. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101089. _this._renderTargetsRenderTime.endMonitoring(false);
  101090. });
  101091. }
  101092. else {
  101093. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101094. this._onBeforeRenderTargetsRenderObserver = null;
  101095. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101096. this._onAfterRenderTargetsRenderObserver = null;
  101097. }
  101098. },
  101099. enumerable: true,
  101100. configurable: true
  101101. });
  101102. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101103. /**
  101104. * Gets the perf counter used for particles render time
  101105. */
  101106. get: function () {
  101107. return this._particlesRenderTime;
  101108. },
  101109. enumerable: true,
  101110. configurable: true
  101111. });
  101112. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101113. /**
  101114. * Gets the particles render time capture status
  101115. */
  101116. get: function () {
  101117. return this._captureParticlesRenderTime;
  101118. },
  101119. /**
  101120. * Enable or disable the particles render time capture
  101121. */
  101122. set: function (value) {
  101123. var _this = this;
  101124. if (value === this._captureParticlesRenderTime) {
  101125. return;
  101126. }
  101127. this._captureParticlesRenderTime = value;
  101128. if (value) {
  101129. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101130. BABYLON.Tools.StartPerformanceCounter("Particles");
  101131. _this._particlesRenderTime.beginMonitoring();
  101132. });
  101133. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101134. BABYLON.Tools.EndPerformanceCounter("Particles");
  101135. _this._particlesRenderTime.endMonitoring(false);
  101136. });
  101137. }
  101138. else {
  101139. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101140. this._onBeforeParticlesRenderingObserver = null;
  101141. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101142. this._onAfterParticlesRenderingObserver = null;
  101143. }
  101144. },
  101145. enumerable: true,
  101146. configurable: true
  101147. });
  101148. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101149. /**
  101150. * Gets the perf counter used for sprites render time
  101151. */
  101152. get: function () {
  101153. return this._spritesRenderTime;
  101154. },
  101155. enumerable: true,
  101156. configurable: true
  101157. });
  101158. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101159. /**
  101160. * Gets the sprites render time capture status
  101161. */
  101162. get: function () {
  101163. return this._captureSpritesRenderTime;
  101164. },
  101165. /**
  101166. * Enable or disable the sprites render time capture
  101167. */
  101168. set: function (value) {
  101169. var _this = this;
  101170. if (value === this._captureSpritesRenderTime) {
  101171. return;
  101172. }
  101173. this._captureSpritesRenderTime = value;
  101174. if (value) {
  101175. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101176. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101177. _this._spritesRenderTime.beginMonitoring();
  101178. });
  101179. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101180. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101181. _this._spritesRenderTime.endMonitoring(false);
  101182. });
  101183. }
  101184. else {
  101185. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101186. this._onBeforeSpritesRenderingObserver = null;
  101187. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101188. this._onAfterSpritesRenderingObserver = null;
  101189. }
  101190. },
  101191. enumerable: true,
  101192. configurable: true
  101193. });
  101194. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101195. /**
  101196. * Gets the perf counter used for physics time
  101197. */
  101198. get: function () {
  101199. return this._physicsTime;
  101200. },
  101201. enumerable: true,
  101202. configurable: true
  101203. });
  101204. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101205. /**
  101206. * Gets the physics time capture status
  101207. */
  101208. get: function () {
  101209. return this._capturePhysicsTime;
  101210. },
  101211. /**
  101212. * Enable or disable the physics time capture
  101213. */
  101214. set: function (value) {
  101215. var _this = this;
  101216. if (value === this._capturePhysicsTime) {
  101217. return;
  101218. }
  101219. this._capturePhysicsTime = value;
  101220. if (value) {
  101221. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101222. BABYLON.Tools.StartPerformanceCounter("Physics");
  101223. _this._physicsTime.beginMonitoring();
  101224. });
  101225. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101226. BABYLON.Tools.EndPerformanceCounter("Physics");
  101227. _this._physicsTime.endMonitoring();
  101228. });
  101229. }
  101230. else {
  101231. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101232. this._onBeforePhysicsObserver = null;
  101233. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101234. this._onAfterPhysicsObserver = null;
  101235. }
  101236. },
  101237. enumerable: true,
  101238. configurable: true
  101239. });
  101240. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101241. /**
  101242. * Gets the perf counter used for animations time
  101243. */
  101244. get: function () {
  101245. return this._animationsTime;
  101246. },
  101247. enumerable: true,
  101248. configurable: true
  101249. });
  101250. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101251. /**
  101252. * Gets the animations time capture status
  101253. */
  101254. get: function () {
  101255. return this._captureAnimationsTime;
  101256. },
  101257. /**
  101258. * Enable or disable the animations time capture
  101259. */
  101260. set: function (value) {
  101261. var _this = this;
  101262. if (value === this._captureAnimationsTime) {
  101263. return;
  101264. }
  101265. this._captureAnimationsTime = value;
  101266. if (value) {
  101267. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101268. _this._animationsTime.endMonitoring();
  101269. });
  101270. }
  101271. else {
  101272. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101273. this._onAfterAnimationsObserver = null;
  101274. }
  101275. },
  101276. enumerable: true,
  101277. configurable: true
  101278. });
  101279. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101280. /**
  101281. * Gets the perf counter used for frame time capture
  101282. */
  101283. get: function () {
  101284. return this._frameTime;
  101285. },
  101286. enumerable: true,
  101287. configurable: true
  101288. });
  101289. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101290. /**
  101291. * Gets the frame time capture status
  101292. */
  101293. get: function () {
  101294. return this._captureFrameTime;
  101295. },
  101296. /**
  101297. * Enable or disable the frame time capture
  101298. */
  101299. set: function (value) {
  101300. this._captureFrameTime = value;
  101301. },
  101302. enumerable: true,
  101303. configurable: true
  101304. });
  101305. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101306. /**
  101307. * Gets the perf counter used for inter-frames time capture
  101308. */
  101309. get: function () {
  101310. return this._interFrameTime;
  101311. },
  101312. enumerable: true,
  101313. configurable: true
  101314. });
  101315. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101316. /**
  101317. * Gets the inter-frames time capture status
  101318. */
  101319. get: function () {
  101320. return this._captureInterFrameTime;
  101321. },
  101322. /**
  101323. * Enable or disable the inter-frames time capture
  101324. */
  101325. set: function (value) {
  101326. this._captureInterFrameTime = value;
  101327. },
  101328. enumerable: true,
  101329. configurable: true
  101330. });
  101331. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101332. /**
  101333. * Gets the perf counter used for render time capture
  101334. */
  101335. get: function () {
  101336. return this._renderTime;
  101337. },
  101338. enumerable: true,
  101339. configurable: true
  101340. });
  101341. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101342. /**
  101343. * Gets the render time capture status
  101344. */
  101345. get: function () {
  101346. return this._captureRenderTime;
  101347. },
  101348. /**
  101349. * Enable or disable the render time capture
  101350. */
  101351. set: function (value) {
  101352. var _this = this;
  101353. if (value === this._captureRenderTime) {
  101354. return;
  101355. }
  101356. this._captureRenderTime = value;
  101357. if (value) {
  101358. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101359. _this._renderTime.beginMonitoring();
  101360. BABYLON.Tools.StartPerformanceCounter("Main render");
  101361. });
  101362. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101363. _this._renderTime.endMonitoring(false);
  101364. BABYLON.Tools.EndPerformanceCounter("Main render");
  101365. });
  101366. }
  101367. else {
  101368. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101369. this._onBeforeDrawPhaseObserver = null;
  101370. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101371. this._onAfterDrawPhaseObserver = null;
  101372. }
  101373. },
  101374. enumerable: true,
  101375. configurable: true
  101376. });
  101377. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101378. /**
  101379. * Gets the perf counter used for camera render time capture
  101380. */
  101381. get: function () {
  101382. return this._cameraRenderTime;
  101383. },
  101384. enumerable: true,
  101385. configurable: true
  101386. });
  101387. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101388. /**
  101389. * Gets the camera render time capture status
  101390. */
  101391. get: function () {
  101392. return this._captureCameraRenderTime;
  101393. },
  101394. /**
  101395. * Enable or disable the camera render time capture
  101396. */
  101397. set: function (value) {
  101398. var _this = this;
  101399. if (value === this._captureCameraRenderTime) {
  101400. return;
  101401. }
  101402. this._captureCameraRenderTime = value;
  101403. if (value) {
  101404. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101405. _this._cameraRenderTime.beginMonitoring();
  101406. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101407. });
  101408. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101409. _this._cameraRenderTime.endMonitoring(false);
  101410. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101411. });
  101412. }
  101413. else {
  101414. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101415. this._onBeforeCameraRenderObserver = null;
  101416. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101417. this._onAfterCameraRenderObserver = null;
  101418. }
  101419. },
  101420. enumerable: true,
  101421. configurable: true
  101422. });
  101423. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101424. /**
  101425. * Gets the perf counter used for draw calls
  101426. */
  101427. get: function () {
  101428. return this.scene.getEngine()._drawCalls;
  101429. },
  101430. enumerable: true,
  101431. configurable: true
  101432. });
  101433. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101434. /**
  101435. * Gets the perf counter used for texture collisions
  101436. */
  101437. get: function () {
  101438. return this.scene.getEngine()._textureCollisions;
  101439. },
  101440. enumerable: true,
  101441. configurable: true
  101442. });
  101443. SceneInstrumentation.prototype.dispose = function () {
  101444. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101445. this._onAfterRenderObserver = null;
  101446. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101447. this._onBeforeActiveMeshesEvaluationObserver = null;
  101448. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101449. this._onAfterActiveMeshesEvaluationObserver = null;
  101450. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101451. this._onBeforeRenderTargetsRenderObserver = null;
  101452. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101453. this._onAfterRenderTargetsRenderObserver = null;
  101454. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101455. this._onBeforeAnimationsObserver = null;
  101456. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101457. this._onBeforeParticlesRenderingObserver = null;
  101458. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101459. this._onAfterParticlesRenderingObserver = null;
  101460. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101461. this._onBeforeSpritesRenderingObserver = null;
  101462. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101463. this._onAfterSpritesRenderingObserver = null;
  101464. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101465. this._onBeforeDrawPhaseObserver = null;
  101466. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101467. this._onAfterDrawPhaseObserver = null;
  101468. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101469. this._onBeforePhysicsObserver = null;
  101470. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101471. this._onAfterPhysicsObserver = null;
  101472. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101473. this._onAfterAnimationsObserver = null;
  101474. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101475. this._onBeforeCameraRenderObserver = null;
  101476. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101477. this._onAfterCameraRenderObserver = null;
  101478. this.scene = null;
  101479. };
  101480. return SceneInstrumentation;
  101481. }());
  101482. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101483. })(BABYLON || (BABYLON = {}));
  101484. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101485. var BABYLON;
  101486. (function (BABYLON) {
  101487. /**
  101488. * @hidden
  101489. **/
  101490. var _TimeToken = /** @class */ (function () {
  101491. function _TimeToken() {
  101492. this._timeElapsedQueryEnded = false;
  101493. }
  101494. return _TimeToken;
  101495. }());
  101496. BABYLON._TimeToken = _TimeToken;
  101497. })(BABYLON || (BABYLON = {}));
  101498. //# sourceMappingURL=babylon.timeToken.js.map
  101499. var BABYLON;
  101500. (function (BABYLON) {
  101501. /**
  101502. * Background material defines definition.
  101503. * @hidden Mainly internal Use
  101504. */
  101505. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101506. __extends(BackgroundMaterialDefines, _super);
  101507. /**
  101508. * Constructor of the defines.
  101509. */
  101510. function BackgroundMaterialDefines() {
  101511. var _this = _super.call(this) || this;
  101512. /**
  101513. * True if the diffuse texture is in use.
  101514. */
  101515. _this.DIFFUSE = false;
  101516. /**
  101517. * The direct UV channel to use.
  101518. */
  101519. _this.DIFFUSEDIRECTUV = 0;
  101520. /**
  101521. * True if the diffuse texture is in gamma space.
  101522. */
  101523. _this.GAMMADIFFUSE = false;
  101524. /**
  101525. * True if the diffuse texture has opacity in the alpha channel.
  101526. */
  101527. _this.DIFFUSEHASALPHA = false;
  101528. /**
  101529. * True if you want the material to fade to transparent at grazing angle.
  101530. */
  101531. _this.OPACITYFRESNEL = false;
  101532. /**
  101533. * True if an extra blur needs to be added in the reflection.
  101534. */
  101535. _this.REFLECTIONBLUR = false;
  101536. /**
  101537. * True if you want the material to fade to reflection at grazing angle.
  101538. */
  101539. _this.REFLECTIONFRESNEL = false;
  101540. /**
  101541. * True if you want the material to falloff as far as you move away from the scene center.
  101542. */
  101543. _this.REFLECTIONFALLOFF = false;
  101544. /**
  101545. * False if the current Webgl implementation does not support the texture lod extension.
  101546. */
  101547. _this.TEXTURELODSUPPORT = false;
  101548. /**
  101549. * True to ensure the data are premultiplied.
  101550. */
  101551. _this.PREMULTIPLYALPHA = false;
  101552. /**
  101553. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101554. */
  101555. _this.USERGBCOLOR = false;
  101556. /**
  101557. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101558. * stays aligned with the desired configuration.
  101559. */
  101560. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101561. /**
  101562. * True to add noise in order to reduce the banding effect.
  101563. */
  101564. _this.NOISE = false;
  101565. /**
  101566. * is the reflection texture in BGR color scheme?
  101567. * Mainly used to solve a bug in ios10 video tag
  101568. */
  101569. _this.REFLECTIONBGR = false;
  101570. _this.IMAGEPROCESSING = false;
  101571. _this.VIGNETTE = false;
  101572. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101573. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101574. _this.TONEMAPPING = false;
  101575. _this.CONTRAST = false;
  101576. _this.COLORCURVES = false;
  101577. _this.COLORGRADING = false;
  101578. _this.COLORGRADING3D = false;
  101579. _this.SAMPLER3DGREENDEPTH = false;
  101580. _this.SAMPLER3DBGRMAP = false;
  101581. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101582. _this.EXPOSURE = false;
  101583. // Reflection.
  101584. _this.REFLECTION = false;
  101585. _this.REFLECTIONMAP_3D = false;
  101586. _this.REFLECTIONMAP_SPHERICAL = false;
  101587. _this.REFLECTIONMAP_PLANAR = false;
  101588. _this.REFLECTIONMAP_CUBIC = false;
  101589. _this.REFLECTIONMAP_PROJECTION = false;
  101590. _this.REFLECTIONMAP_SKYBOX = false;
  101591. _this.REFLECTIONMAP_EXPLICIT = false;
  101592. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101593. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101594. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101595. _this.INVERTCUBICMAP = false;
  101596. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101597. _this.LODINREFLECTIONALPHA = false;
  101598. _this.GAMMAREFLECTION = false;
  101599. _this.RGBDREFLECTION = false;
  101600. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101601. // Default BJS.
  101602. _this.MAINUV1 = false;
  101603. _this.MAINUV2 = false;
  101604. _this.UV1 = false;
  101605. _this.UV2 = false;
  101606. _this.CLIPPLANE = false;
  101607. _this.POINTSIZE = false;
  101608. _this.FOG = false;
  101609. _this.NORMAL = false;
  101610. _this.NUM_BONE_INFLUENCERS = 0;
  101611. _this.BonesPerMesh = 0;
  101612. _this.INSTANCES = false;
  101613. _this.SHADOWFLOAT = false;
  101614. _this.rebuild();
  101615. return _this;
  101616. }
  101617. return BackgroundMaterialDefines;
  101618. }(BABYLON.MaterialDefines));
  101619. /**
  101620. * Background material used to create an efficient environement around your scene.
  101621. */
  101622. var BackgroundMaterial = /** @class */ (function (_super) {
  101623. __extends(BackgroundMaterial, _super);
  101624. /**
  101625. * Instantiates a Background Material in the given scene
  101626. * @param name The friendly name of the material
  101627. * @param scene The scene to add the material to
  101628. */
  101629. function BackgroundMaterial(name, scene) {
  101630. var _this = _super.call(this, name, scene) || this;
  101631. /**
  101632. * Key light Color (multiply against the environement texture)
  101633. */
  101634. _this.primaryColor = BABYLON.Color3.White();
  101635. _this._primaryColorShadowLevel = 0;
  101636. _this._primaryColorHighlightLevel = 0;
  101637. /**
  101638. * Reflection Texture used in the material.
  101639. * Should be author in a specific way for the best result (refer to the documentation).
  101640. */
  101641. _this.reflectionTexture = null;
  101642. /**
  101643. * Reflection Texture level of blur.
  101644. *
  101645. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101646. * texture twice.
  101647. */
  101648. _this.reflectionBlur = 0;
  101649. /**
  101650. * Diffuse Texture used in the material.
  101651. * Should be author in a specific way for the best result (refer to the documentation).
  101652. */
  101653. _this.diffuseTexture = null;
  101654. _this._shadowLights = null;
  101655. /**
  101656. * Specify the list of lights casting shadow on the material.
  101657. * All scene shadow lights will be included if null.
  101658. */
  101659. _this.shadowLights = null;
  101660. /**
  101661. * Helps adjusting the shadow to a softer level if required.
  101662. * 0 means black shadows and 1 means no shadows.
  101663. */
  101664. _this.shadowLevel = 0;
  101665. /**
  101666. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101667. * It is usually zero but might be interesting to modify according to your setup.
  101668. */
  101669. _this.sceneCenter = BABYLON.Vector3.Zero();
  101670. /**
  101671. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101672. * This helps ensuring a nice transition when the camera goes under the ground.
  101673. */
  101674. _this.opacityFresnel = true;
  101675. /**
  101676. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101677. * This helps adding a mirror texture on the ground.
  101678. */
  101679. _this.reflectionFresnel = false;
  101680. /**
  101681. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101682. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101683. */
  101684. _this.reflectionFalloffDistance = 0.0;
  101685. /**
  101686. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101687. */
  101688. _this.reflectionAmount = 1.0;
  101689. /**
  101690. * This specifies the weight of the reflection at grazing angle.
  101691. */
  101692. _this.reflectionReflectance0 = 0.05;
  101693. /**
  101694. * This specifies the weight of the reflection at a perpendicular point of view.
  101695. */
  101696. _this.reflectionReflectance90 = 0.5;
  101697. /**
  101698. * Helps to directly use the maps channels instead of their level.
  101699. */
  101700. _this.useRGBColor = true;
  101701. /**
  101702. * This helps reducing the banding effect that could occur on the background.
  101703. */
  101704. _this.enableNoise = false;
  101705. _this._fovMultiplier = 1.0;
  101706. /**
  101707. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101708. */
  101709. _this.useEquirectangularFOV = false;
  101710. _this._maxSimultaneousLights = 4;
  101711. /**
  101712. * Number of Simultaneous lights allowed on the material.
  101713. */
  101714. _this.maxSimultaneousLights = 4;
  101715. /**
  101716. * Keep track of the image processing observer to allow dispose and replace.
  101717. */
  101718. _this._imageProcessingObserver = null;
  101719. /**
  101720. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101721. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101722. */
  101723. _this.switchToBGR = false;
  101724. // Temp values kept as cache in the material.
  101725. _this._renderTargets = new BABYLON.SmartArray(16);
  101726. _this._reflectionControls = BABYLON.Vector4.Zero();
  101727. _this._white = BABYLON.Color3.White();
  101728. _this._primaryShadowColor = BABYLON.Color3.Black();
  101729. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101730. // Setup the default processing configuration to the scene.
  101731. _this._attachImageProcessingConfiguration(null);
  101732. _this.getRenderTargetTextures = function () {
  101733. _this._renderTargets.reset();
  101734. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101735. _this._renderTargets.push(_this._diffuseTexture);
  101736. }
  101737. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101738. _this._renderTargets.push(_this._reflectionTexture);
  101739. }
  101740. return _this._renderTargets;
  101741. };
  101742. return _this;
  101743. }
  101744. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101745. /**
  101746. * Experimental Internal Use Only.
  101747. *
  101748. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101749. * This acts as a helper to set the primary color to a more "human friendly" value.
  101750. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101751. * output color as close as possible from the chosen value.
  101752. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101753. * part of lighting setup.)
  101754. */
  101755. get: function () {
  101756. return this.__perceptualColor;
  101757. },
  101758. set: function (value) {
  101759. this.__perceptualColor = value;
  101760. this._computePrimaryColorFromPerceptualColor();
  101761. this._markAllSubMeshesAsLightsDirty();
  101762. },
  101763. enumerable: true,
  101764. configurable: true
  101765. });
  101766. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101767. /**
  101768. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101769. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101770. */
  101771. get: function () {
  101772. return this._primaryColorShadowLevel;
  101773. },
  101774. set: function (value) {
  101775. this._primaryColorShadowLevel = value;
  101776. this._computePrimaryColors();
  101777. this._markAllSubMeshesAsLightsDirty();
  101778. },
  101779. enumerable: true,
  101780. configurable: true
  101781. });
  101782. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101783. /**
  101784. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101785. * The primary color is used at the level chosen to define what the white area would look.
  101786. */
  101787. get: function () {
  101788. return this._primaryColorHighlightLevel;
  101789. },
  101790. set: function (value) {
  101791. this._primaryColorHighlightLevel = value;
  101792. this._computePrimaryColors();
  101793. this._markAllSubMeshesAsLightsDirty();
  101794. },
  101795. enumerable: true,
  101796. configurable: true
  101797. });
  101798. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101799. /**
  101800. * Sets the reflection reflectance fresnel values according to the default standard
  101801. * empirically know to work well :-)
  101802. */
  101803. set: function (value) {
  101804. var reflectionWeight = value;
  101805. if (reflectionWeight < 0.5) {
  101806. reflectionWeight = reflectionWeight * 2.0;
  101807. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101808. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101809. }
  101810. else {
  101811. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101812. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101813. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101814. }
  101815. },
  101816. enumerable: true,
  101817. configurable: true
  101818. });
  101819. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101820. /**
  101821. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101822. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101823. * Recommended to be keep at 1.0 except for special cases.
  101824. */
  101825. get: function () {
  101826. return this._fovMultiplier;
  101827. },
  101828. set: function (value) {
  101829. if (isNaN(value)) {
  101830. value = 1.0;
  101831. }
  101832. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101833. },
  101834. enumerable: true,
  101835. configurable: true
  101836. });
  101837. /**
  101838. * Attaches a new image processing configuration to the PBR Material.
  101839. * @param configuration (if null the scene configuration will be use)
  101840. */
  101841. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101842. var _this = this;
  101843. if (configuration === this._imageProcessingConfiguration) {
  101844. return;
  101845. }
  101846. // Detaches observer.
  101847. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101848. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101849. }
  101850. // Pick the scene configuration if needed.
  101851. if (!configuration) {
  101852. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101853. }
  101854. else {
  101855. this._imageProcessingConfiguration = configuration;
  101856. }
  101857. // Attaches observer.
  101858. if (this._imageProcessingConfiguration) {
  101859. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101860. _this._computePrimaryColorFromPerceptualColor();
  101861. _this._markAllSubMeshesAsImageProcessingDirty();
  101862. });
  101863. }
  101864. };
  101865. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101866. /**
  101867. * Gets the image processing configuration used either in this material.
  101868. */
  101869. get: function () {
  101870. return this._imageProcessingConfiguration;
  101871. },
  101872. /**
  101873. * Sets the Default image processing configuration used either in the this material.
  101874. *
  101875. * If sets to null, the scene one is in use.
  101876. */
  101877. set: function (value) {
  101878. this._attachImageProcessingConfiguration(value);
  101879. // Ensure the effect will be rebuilt.
  101880. this._markAllSubMeshesAsTexturesDirty();
  101881. },
  101882. enumerable: true,
  101883. configurable: true
  101884. });
  101885. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101886. /**
  101887. * Gets wether the color curves effect is enabled.
  101888. */
  101889. get: function () {
  101890. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101891. },
  101892. /**
  101893. * Sets wether the color curves effect is enabled.
  101894. */
  101895. set: function (value) {
  101896. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101897. },
  101898. enumerable: true,
  101899. configurable: true
  101900. });
  101901. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101902. /**
  101903. * Gets wether the color grading effect is enabled.
  101904. */
  101905. get: function () {
  101906. return this.imageProcessingConfiguration.colorGradingEnabled;
  101907. },
  101908. /**
  101909. * Gets wether the color grading effect is enabled.
  101910. */
  101911. set: function (value) {
  101912. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101913. },
  101914. enumerable: true,
  101915. configurable: true
  101916. });
  101917. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101918. /**
  101919. * Gets wether tonemapping is enabled or not.
  101920. */
  101921. get: function () {
  101922. return this._imageProcessingConfiguration.toneMappingEnabled;
  101923. },
  101924. /**
  101925. * Sets wether tonemapping is enabled or not
  101926. */
  101927. set: function (value) {
  101928. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101929. },
  101930. enumerable: true,
  101931. configurable: true
  101932. });
  101933. ;
  101934. ;
  101935. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101936. /**
  101937. * The camera exposure used on this material.
  101938. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101939. * This corresponds to a photographic exposure.
  101940. */
  101941. get: function () {
  101942. return this._imageProcessingConfiguration.exposure;
  101943. },
  101944. /**
  101945. * The camera exposure used on this material.
  101946. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101947. * This corresponds to a photographic exposure.
  101948. */
  101949. set: function (value) {
  101950. this._imageProcessingConfiguration.exposure = value;
  101951. },
  101952. enumerable: true,
  101953. configurable: true
  101954. });
  101955. ;
  101956. ;
  101957. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101958. /**
  101959. * Gets The camera contrast used on this material.
  101960. */
  101961. get: function () {
  101962. return this._imageProcessingConfiguration.contrast;
  101963. },
  101964. /**
  101965. * Sets The camera contrast used on this material.
  101966. */
  101967. set: function (value) {
  101968. this._imageProcessingConfiguration.contrast = value;
  101969. },
  101970. enumerable: true,
  101971. configurable: true
  101972. });
  101973. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101974. /**
  101975. * Gets the Color Grading 2D Lookup Texture.
  101976. */
  101977. get: function () {
  101978. return this._imageProcessingConfiguration.colorGradingTexture;
  101979. },
  101980. /**
  101981. * Sets the Color Grading 2D Lookup Texture.
  101982. */
  101983. set: function (value) {
  101984. this.imageProcessingConfiguration.colorGradingTexture = value;
  101985. },
  101986. enumerable: true,
  101987. configurable: true
  101988. });
  101989. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101990. /**
  101991. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101992. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101993. * 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;
  101994. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101995. */
  101996. get: function () {
  101997. return this.imageProcessingConfiguration.colorCurves;
  101998. },
  101999. /**
  102000. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102001. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102002. * 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;
  102003. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102004. */
  102005. set: function (value) {
  102006. this.imageProcessingConfiguration.colorCurves = value;
  102007. },
  102008. enumerable: true,
  102009. configurable: true
  102010. });
  102011. /**
  102012. * The entire material has been created in order to prevent overdraw.
  102013. * @returns false
  102014. */
  102015. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102016. return true;
  102017. };
  102018. /**
  102019. * The entire material has been created in order to prevent overdraw.
  102020. * @returns true if blending is enable
  102021. */
  102022. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102023. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102024. };
  102025. /**
  102026. * Checks wether the material is ready to be rendered for a given mesh.
  102027. * @param mesh The mesh to render
  102028. * @param subMesh The submesh to check against
  102029. * @param useInstances Specify wether or not the material is used with instances
  102030. * @returns true if all the dependencies are ready (Textures, Effects...)
  102031. */
  102032. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102033. var _this = this;
  102034. if (useInstances === void 0) { useInstances = false; }
  102035. if (subMesh.effect && this.isFrozen) {
  102036. if (this._wasPreviouslyReady) {
  102037. return true;
  102038. }
  102039. }
  102040. if (!subMesh._materialDefines) {
  102041. subMesh._materialDefines = new BackgroundMaterialDefines();
  102042. }
  102043. var scene = this.getScene();
  102044. var defines = subMesh._materialDefines;
  102045. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102046. if (defines._renderId === scene.getRenderId()) {
  102047. return true;
  102048. }
  102049. }
  102050. var engine = scene.getEngine();
  102051. // Lights
  102052. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102053. defines._needNormals = true;
  102054. // Textures
  102055. if (defines._areTexturesDirty) {
  102056. defines._needUVs = false;
  102057. if (scene.texturesEnabled) {
  102058. if (scene.getEngine().getCaps().textureLOD) {
  102059. defines.TEXTURELODSUPPORT = true;
  102060. }
  102061. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102062. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102063. return false;
  102064. }
  102065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102066. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102067. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102068. defines.OPACITYFRESNEL = this._opacityFresnel;
  102069. }
  102070. else {
  102071. defines.DIFFUSE = false;
  102072. defines.DIFFUSEHASALPHA = false;
  102073. defines.GAMMADIFFUSE = false;
  102074. defines.OPACITYFRESNEL = false;
  102075. }
  102076. var reflectionTexture = this._reflectionTexture;
  102077. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102078. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102079. return false;
  102080. }
  102081. defines.REFLECTION = true;
  102082. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102083. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102084. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102085. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102086. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102087. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102088. defines.REFLECTIONBGR = this.switchToBGR;
  102089. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102090. defines.INVERTCUBICMAP = true;
  102091. }
  102092. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102093. switch (reflectionTexture.coordinatesMode) {
  102094. case BABYLON.Texture.EXPLICIT_MODE:
  102095. defines.REFLECTIONMAP_EXPLICIT = true;
  102096. break;
  102097. case BABYLON.Texture.PLANAR_MODE:
  102098. defines.REFLECTIONMAP_PLANAR = true;
  102099. break;
  102100. case BABYLON.Texture.PROJECTION_MODE:
  102101. defines.REFLECTIONMAP_PROJECTION = true;
  102102. break;
  102103. case BABYLON.Texture.SKYBOX_MODE:
  102104. defines.REFLECTIONMAP_SKYBOX = true;
  102105. break;
  102106. case BABYLON.Texture.SPHERICAL_MODE:
  102107. defines.REFLECTIONMAP_SPHERICAL = true;
  102108. break;
  102109. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102110. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102111. break;
  102112. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102113. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102114. break;
  102115. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102116. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102117. break;
  102118. case BABYLON.Texture.CUBIC_MODE:
  102119. case BABYLON.Texture.INVCUBIC_MODE:
  102120. default:
  102121. defines.REFLECTIONMAP_CUBIC = true;
  102122. break;
  102123. }
  102124. if (this.reflectionFresnel) {
  102125. defines.REFLECTIONFRESNEL = true;
  102126. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102127. this._reflectionControls.x = this.reflectionAmount;
  102128. this._reflectionControls.y = this.reflectionReflectance0;
  102129. this._reflectionControls.z = this.reflectionReflectance90;
  102130. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102131. }
  102132. else {
  102133. defines.REFLECTIONFRESNEL = false;
  102134. defines.REFLECTIONFALLOFF = false;
  102135. }
  102136. }
  102137. else {
  102138. defines.REFLECTION = false;
  102139. defines.REFLECTIONFRESNEL = false;
  102140. defines.REFLECTIONFALLOFF = false;
  102141. defines.REFLECTIONBLUR = false;
  102142. defines.REFLECTIONMAP_3D = false;
  102143. defines.REFLECTIONMAP_SPHERICAL = false;
  102144. defines.REFLECTIONMAP_PLANAR = false;
  102145. defines.REFLECTIONMAP_CUBIC = false;
  102146. defines.REFLECTIONMAP_PROJECTION = false;
  102147. defines.REFLECTIONMAP_SKYBOX = false;
  102148. defines.REFLECTIONMAP_EXPLICIT = false;
  102149. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102150. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102151. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102152. defines.INVERTCUBICMAP = false;
  102153. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102154. defines.LODINREFLECTIONALPHA = false;
  102155. defines.GAMMAREFLECTION = false;
  102156. defines.RGBDREFLECTION = false;
  102157. }
  102158. }
  102159. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102160. defines.USERGBCOLOR = this._useRGBColor;
  102161. defines.NOISE = this._enableNoise;
  102162. }
  102163. if (defines._areLightsDirty) {
  102164. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102165. }
  102166. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102167. if (!this._imageProcessingConfiguration.isReady()) {
  102168. return false;
  102169. }
  102170. this._imageProcessingConfiguration.prepareDefines(defines);
  102171. }
  102172. // Misc.
  102173. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102174. // Values that need to be evaluated on every frame
  102175. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102176. // Attribs
  102177. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102178. if (mesh) {
  102179. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102180. mesh.createNormals(true);
  102181. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102182. }
  102183. }
  102184. }
  102185. // Get correct effect
  102186. if (defines.isDirty) {
  102187. defines.markAsProcessed();
  102188. scene.resetCachedMaterial();
  102189. // Fallbacks
  102190. var fallbacks = new BABYLON.EffectFallbacks();
  102191. if (defines.FOG) {
  102192. fallbacks.addFallback(0, "FOG");
  102193. }
  102194. if (defines.POINTSIZE) {
  102195. fallbacks.addFallback(1, "POINTSIZE");
  102196. }
  102197. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102198. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102199. fallbacks.addCPUSkinningFallback(0, mesh);
  102200. }
  102201. //Attributes
  102202. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102203. if (defines.NORMAL) {
  102204. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102205. }
  102206. if (defines.UV1) {
  102207. attribs.push(BABYLON.VertexBuffer.UVKind);
  102208. }
  102209. if (defines.UV2) {
  102210. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102211. }
  102212. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102213. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102214. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102215. "vFogInfos", "vFogColor", "pointSize",
  102216. "vClipPlane", "mBones",
  102217. "vPrimaryColor", "vPrimaryColorShadow",
  102218. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102219. "shadowLevel", "alpha",
  102220. "vBackgroundCenter", "vReflectionControl",
  102221. "vDiffuseInfos", "diffuseMatrix",
  102222. ];
  102223. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102224. var uniformBuffers = ["Material", "Scene"];
  102225. if (BABYLON.ImageProcessingConfiguration) {
  102226. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102227. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102228. }
  102229. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102230. uniformsNames: uniforms,
  102231. uniformBuffersNames: uniformBuffers,
  102232. samplers: samplers,
  102233. defines: defines,
  102234. maxSimultaneousLights: this._maxSimultaneousLights
  102235. });
  102236. var onCompiled = function (effect) {
  102237. if (_this.onCompiled) {
  102238. _this.onCompiled(effect);
  102239. }
  102240. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102241. };
  102242. var join = defines.toString();
  102243. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102244. attributes: attribs,
  102245. uniformsNames: uniforms,
  102246. uniformBuffersNames: uniformBuffers,
  102247. samplers: samplers,
  102248. defines: join,
  102249. fallbacks: fallbacks,
  102250. onCompiled: onCompiled,
  102251. onError: this.onError,
  102252. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102253. }, engine), defines);
  102254. this.buildUniformLayout();
  102255. }
  102256. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102257. return false;
  102258. }
  102259. defines._renderId = scene.getRenderId();
  102260. this._wasPreviouslyReady = true;
  102261. return true;
  102262. };
  102263. /**
  102264. * Compute the primary color according to the chosen perceptual color.
  102265. */
  102266. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102267. if (!this.__perceptualColor) {
  102268. return;
  102269. }
  102270. this._primaryColor.copyFrom(this.__perceptualColor);
  102271. // Revert gamma space.
  102272. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102273. // Revert image processing configuration.
  102274. if (this._imageProcessingConfiguration) {
  102275. // Revert Exposure.
  102276. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102277. }
  102278. this._computePrimaryColors();
  102279. };
  102280. /**
  102281. * Compute the highlights and shadow colors according to their chosen levels.
  102282. */
  102283. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102284. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102285. return;
  102286. }
  102287. // Find the highlight color based on the configuration.
  102288. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102289. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102290. // Find the shadow color based on the configuration.
  102291. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102292. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102293. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102294. };
  102295. /**
  102296. * Build the uniform buffer used in the material.
  102297. */
  102298. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102299. // Order is important !
  102300. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102301. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102302. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102303. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102304. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102305. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102306. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102307. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102308. this._uniformBuffer.addUniform("pointSize", 1);
  102309. this._uniformBuffer.addUniform("shadowLevel", 1);
  102310. this._uniformBuffer.addUniform("alpha", 1);
  102311. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102312. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102313. this._uniformBuffer.create();
  102314. };
  102315. /**
  102316. * Unbind the material.
  102317. */
  102318. BackgroundMaterial.prototype.unbind = function () {
  102319. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102320. this._uniformBuffer.setTexture("diffuseSampler", null);
  102321. }
  102322. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102323. this._uniformBuffer.setTexture("reflectionSampler", null);
  102324. }
  102325. _super.prototype.unbind.call(this);
  102326. };
  102327. /**
  102328. * Bind only the world matrix to the material.
  102329. * @param world The world matrix to bind.
  102330. */
  102331. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102332. this._activeEffect.setMatrix("world", world);
  102333. };
  102334. /**
  102335. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102336. * @param world The world matrix to bind.
  102337. * @param subMesh The submesh to bind for.
  102338. */
  102339. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102340. var scene = this.getScene();
  102341. var defines = subMesh._materialDefines;
  102342. if (!defines) {
  102343. return;
  102344. }
  102345. var effect = subMesh.effect;
  102346. if (!effect) {
  102347. return;
  102348. }
  102349. this._activeEffect = effect;
  102350. // Matrices
  102351. this.bindOnlyWorldMatrix(world);
  102352. // Bones
  102353. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102354. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102355. if (mustRebind) {
  102356. this._uniformBuffer.bindToEffect(effect, "Material");
  102357. this.bindViewProjection(effect);
  102358. var reflectionTexture = this._reflectionTexture;
  102359. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102360. // Texture uniforms
  102361. if (scene.texturesEnabled) {
  102362. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102363. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102364. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102365. }
  102366. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102367. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102368. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102369. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102370. }
  102371. }
  102372. if (this.shadowLevel > 0) {
  102373. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102374. }
  102375. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102376. // Point size
  102377. if (this.pointsCloud) {
  102378. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102379. }
  102380. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102381. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102382. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102383. }
  102384. else {
  102385. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102386. }
  102387. }
  102388. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102389. // Textures
  102390. if (scene.texturesEnabled) {
  102391. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102392. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102393. }
  102394. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102395. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102396. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102397. }
  102398. else if (!defines.REFLECTIONBLUR) {
  102399. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102400. }
  102401. else {
  102402. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102403. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102404. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102405. }
  102406. if (defines.REFLECTIONFRESNEL) {
  102407. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102408. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102409. }
  102410. }
  102411. }
  102412. // Clip plane
  102413. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102414. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102415. }
  102416. if (mustRebind || !this.isFrozen) {
  102417. if (scene.lightsEnabled) {
  102418. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102419. }
  102420. // View
  102421. this.bindView(effect);
  102422. // Fog
  102423. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102424. // image processing
  102425. if (this._imageProcessingConfiguration) {
  102426. this._imageProcessingConfiguration.bind(this._activeEffect);
  102427. }
  102428. }
  102429. this._uniformBuffer.update();
  102430. this._afterBind(mesh, this._activeEffect);
  102431. };
  102432. /**
  102433. * Dispose the material.
  102434. * @param forceDisposeEffect Force disposal of the associated effect.
  102435. * @param forceDisposeTextures Force disposal of the associated textures.
  102436. */
  102437. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102438. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102439. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102440. if (forceDisposeTextures) {
  102441. if (this.diffuseTexture) {
  102442. this.diffuseTexture.dispose();
  102443. }
  102444. if (this.reflectionTexture) {
  102445. this.reflectionTexture.dispose();
  102446. }
  102447. }
  102448. this._renderTargets.dispose();
  102449. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102450. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102451. }
  102452. _super.prototype.dispose.call(this, forceDisposeEffect);
  102453. };
  102454. /**
  102455. * Clones the material.
  102456. * @param name The cloned name.
  102457. * @returns The cloned material.
  102458. */
  102459. BackgroundMaterial.prototype.clone = function (name) {
  102460. var _this = this;
  102461. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102462. };
  102463. /**
  102464. * Serializes the current material to its JSON representation.
  102465. * @returns The JSON representation.
  102466. */
  102467. BackgroundMaterial.prototype.serialize = function () {
  102468. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102469. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102470. return serializationObject;
  102471. };
  102472. /**
  102473. * Gets the class name of the material
  102474. * @returns "BackgroundMaterial"
  102475. */
  102476. BackgroundMaterial.prototype.getClassName = function () {
  102477. return "BackgroundMaterial";
  102478. };
  102479. /**
  102480. * Parse a JSON input to create back a background material.
  102481. * @param source The JSON data to parse
  102482. * @param scene The scene to create the parsed material in
  102483. * @param rootUrl The root url of the assets the material depends upon
  102484. * @returns the instantiated BackgroundMaterial.
  102485. */
  102486. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102487. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102488. };
  102489. /**
  102490. * Standard reflectance value at parallel view angle.
  102491. */
  102492. BackgroundMaterial.StandardReflectance0 = 0.05;
  102493. /**
  102494. * Standard reflectance value at grazing angle.
  102495. */
  102496. BackgroundMaterial.StandardReflectance90 = 0.5;
  102497. __decorate([
  102498. BABYLON.serializeAsColor3()
  102499. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102500. __decorate([
  102501. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102502. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102503. __decorate([
  102504. BABYLON.serializeAsColor3()
  102505. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102506. __decorate([
  102507. BABYLON.serialize()
  102508. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102509. __decorate([
  102510. BABYLON.serialize()
  102511. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102512. __decorate([
  102513. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102514. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102515. __decorate([
  102516. BABYLON.serializeAsTexture()
  102517. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102518. __decorate([
  102519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102520. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102521. __decorate([
  102522. BABYLON.serialize()
  102523. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102524. __decorate([
  102525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102526. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102527. __decorate([
  102528. BABYLON.serializeAsTexture()
  102529. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102530. __decorate([
  102531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102532. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102533. __decorate([
  102534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102535. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102536. __decorate([
  102537. BABYLON.serialize()
  102538. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102539. __decorate([
  102540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102541. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102542. __decorate([
  102543. BABYLON.serializeAsVector3()
  102544. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102545. __decorate([
  102546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102547. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102548. __decorate([
  102549. BABYLON.serialize()
  102550. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102551. __decorate([
  102552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102553. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102554. __decorate([
  102555. BABYLON.serialize()
  102556. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102557. __decorate([
  102558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102559. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102560. __decorate([
  102561. BABYLON.serialize()
  102562. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102563. __decorate([
  102564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102565. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102566. __decorate([
  102567. BABYLON.serialize()
  102568. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102569. __decorate([
  102570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102571. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102572. __decorate([
  102573. BABYLON.serialize()
  102574. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102575. __decorate([
  102576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102577. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102578. __decorate([
  102579. BABYLON.serialize()
  102580. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102581. __decorate([
  102582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102583. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102584. __decorate([
  102585. BABYLON.serialize()
  102586. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102587. __decorate([
  102588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102589. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102590. __decorate([
  102591. BABYLON.serialize()
  102592. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102593. __decorate([
  102594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102595. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102596. __decorate([
  102597. BABYLON.serialize()
  102598. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102599. __decorate([
  102600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102601. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102602. __decorate([
  102603. BABYLON.serializeAsImageProcessingConfiguration()
  102604. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102605. return BackgroundMaterial;
  102606. }(BABYLON.PushMaterial));
  102607. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102608. })(BABYLON || (BABYLON = {}));
  102609. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102610. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102611. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102612. s = arguments[i];
  102613. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102614. t[p] = s[p];
  102615. }
  102616. return t;
  102617. };
  102618. var BABYLON;
  102619. (function (BABYLON) {
  102620. /**
  102621. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102622. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102623. * It also helps with the default setup of your imageProcessing configuration.
  102624. */
  102625. var EnvironmentHelper = /** @class */ (function () {
  102626. /**
  102627. * constructor
  102628. * @param options
  102629. * @param scene The scene to add the material to
  102630. */
  102631. function EnvironmentHelper(options, scene) {
  102632. var _this = this;
  102633. this._errorHandler = function (message, exception) {
  102634. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102635. };
  102636. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102637. this._scene = scene;
  102638. this.onErrorObservable = new BABYLON.Observable();
  102639. this._setupBackground();
  102640. this._setupImageProcessing();
  102641. }
  102642. /**
  102643. * Creates the default options for the helper.
  102644. */
  102645. EnvironmentHelper._getDefaultOptions = function () {
  102646. return {
  102647. createGround: true,
  102648. groundSize: 15,
  102649. groundTexture: this._groundTextureCDNUrl,
  102650. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102651. groundOpacity: 0.9,
  102652. enableGroundShadow: true,
  102653. groundShadowLevel: 0.5,
  102654. enableGroundMirror: false,
  102655. groundMirrorSizeRatio: 0.3,
  102656. groundMirrorBlurKernel: 64,
  102657. groundMirrorAmount: 1,
  102658. groundMirrorFresnelWeight: 1,
  102659. groundMirrorFallOffDistance: 0,
  102660. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102661. groundYBias: 0.00001,
  102662. createSkybox: true,
  102663. skyboxSize: 20,
  102664. skyboxTexture: this._skyboxTextureCDNUrl,
  102665. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102666. backgroundYRotation: 0,
  102667. sizeAuto: true,
  102668. rootPosition: BABYLON.Vector3.Zero(),
  102669. setupImageProcessing: true,
  102670. environmentTexture: this._environmentTextureCDNUrl,
  102671. cameraExposure: 0.8,
  102672. cameraContrast: 1.2,
  102673. toneMappingEnabled: true,
  102674. };
  102675. };
  102676. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102677. /**
  102678. * Gets the root mesh created by the helper.
  102679. */
  102680. get: function () {
  102681. return this._rootMesh;
  102682. },
  102683. enumerable: true,
  102684. configurable: true
  102685. });
  102686. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102687. /**
  102688. * Gets the skybox created by the helper.
  102689. */
  102690. get: function () {
  102691. return this._skybox;
  102692. },
  102693. enumerable: true,
  102694. configurable: true
  102695. });
  102696. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102697. /**
  102698. * Gets the skybox texture created by the helper.
  102699. */
  102700. get: function () {
  102701. return this._skyboxTexture;
  102702. },
  102703. enumerable: true,
  102704. configurable: true
  102705. });
  102706. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102707. /**
  102708. * Gets the skybox material created by the helper.
  102709. */
  102710. get: function () {
  102711. return this._skyboxMaterial;
  102712. },
  102713. enumerable: true,
  102714. configurable: true
  102715. });
  102716. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102717. /**
  102718. * Gets the ground mesh created by the helper.
  102719. */
  102720. get: function () {
  102721. return this._ground;
  102722. },
  102723. enumerable: true,
  102724. configurable: true
  102725. });
  102726. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102727. /**
  102728. * Gets the ground texture created by the helper.
  102729. */
  102730. get: function () {
  102731. return this._groundTexture;
  102732. },
  102733. enumerable: true,
  102734. configurable: true
  102735. });
  102736. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102737. /**
  102738. * Gets the ground mirror created by the helper.
  102739. */
  102740. get: function () {
  102741. return this._groundMirror;
  102742. },
  102743. enumerable: true,
  102744. configurable: true
  102745. });
  102746. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102747. /**
  102748. * Gets the ground mirror render list to helps pushing the meshes
  102749. * you wish in the ground reflection.
  102750. */
  102751. get: function () {
  102752. if (this._groundMirror) {
  102753. return this._groundMirror.renderList;
  102754. }
  102755. return null;
  102756. },
  102757. enumerable: true,
  102758. configurable: true
  102759. });
  102760. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102761. /**
  102762. * Gets the ground material created by the helper.
  102763. */
  102764. get: function () {
  102765. return this._groundMaterial;
  102766. },
  102767. enumerable: true,
  102768. configurable: true
  102769. });
  102770. /**
  102771. * Updates the background according to the new options
  102772. * @param options
  102773. */
  102774. EnvironmentHelper.prototype.updateOptions = function (options) {
  102775. var newOptions = __assign({}, this._options, options);
  102776. if (this._ground && !newOptions.createGround) {
  102777. this._ground.dispose();
  102778. this._ground = null;
  102779. }
  102780. if (this._groundMaterial && !newOptions.createGround) {
  102781. this._groundMaterial.dispose();
  102782. this._groundMaterial = null;
  102783. }
  102784. if (this._groundTexture) {
  102785. if (this._options.groundTexture != newOptions.groundTexture) {
  102786. this._groundTexture.dispose();
  102787. this._groundTexture = null;
  102788. }
  102789. }
  102790. if (this._skybox && !newOptions.createSkybox) {
  102791. this._skybox.dispose();
  102792. this._skybox = null;
  102793. }
  102794. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102795. this._skyboxMaterial.dispose();
  102796. this._skyboxMaterial = null;
  102797. }
  102798. if (this._skyboxTexture) {
  102799. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102800. this._skyboxTexture.dispose();
  102801. this._skyboxTexture = null;
  102802. }
  102803. }
  102804. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102805. this._groundMirror.dispose();
  102806. this._groundMirror = null;
  102807. }
  102808. if (this._scene.environmentTexture) {
  102809. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102810. this._scene.environmentTexture.dispose();
  102811. }
  102812. }
  102813. this._options = newOptions;
  102814. this._setupBackground();
  102815. this._setupImageProcessing();
  102816. };
  102817. /**
  102818. * Sets the primary color of all the available elements.
  102819. * @param color the main color to affect to the ground and the background
  102820. */
  102821. EnvironmentHelper.prototype.setMainColor = function (color) {
  102822. if (this.groundMaterial) {
  102823. this.groundMaterial.primaryColor = color;
  102824. }
  102825. if (this.skyboxMaterial) {
  102826. this.skyboxMaterial.primaryColor = color;
  102827. }
  102828. if (this.groundMirror) {
  102829. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102830. }
  102831. };
  102832. /**
  102833. * Setup the image processing according to the specified options.
  102834. */
  102835. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102836. if (this._options.setupImageProcessing) {
  102837. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102838. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102839. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102840. this._setupEnvironmentTexture();
  102841. }
  102842. };
  102843. /**
  102844. * Setup the environment texture according to the specified options.
  102845. */
  102846. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102847. if (this._scene.environmentTexture) {
  102848. return;
  102849. }
  102850. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102851. this._scene.environmentTexture = this._options.environmentTexture;
  102852. return;
  102853. }
  102854. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102855. this._scene.environmentTexture = environmentTexture;
  102856. };
  102857. /**
  102858. * Setup the background according to the specified options.
  102859. */
  102860. EnvironmentHelper.prototype._setupBackground = function () {
  102861. if (!this._rootMesh) {
  102862. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102863. }
  102864. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102865. var sceneSize = this._getSceneSize();
  102866. if (this._options.createGround) {
  102867. this._setupGround(sceneSize);
  102868. this._setupGroundMaterial();
  102869. this._setupGroundDiffuseTexture();
  102870. if (this._options.enableGroundMirror) {
  102871. this._setupGroundMirrorTexture(sceneSize);
  102872. }
  102873. this._setupMirrorInGroundMaterial();
  102874. }
  102875. if (this._options.createSkybox) {
  102876. this._setupSkybox(sceneSize);
  102877. this._setupSkyboxMaterial();
  102878. this._setupSkyboxReflectionTexture();
  102879. }
  102880. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102881. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102882. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102883. };
  102884. /**
  102885. * Get the scene sizes according to the setup.
  102886. */
  102887. EnvironmentHelper.prototype._getSceneSize = function () {
  102888. var _this = this;
  102889. var groundSize = this._options.groundSize;
  102890. var skyboxSize = this._options.skyboxSize;
  102891. var rootPosition = this._options.rootPosition;
  102892. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102893. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102894. }
  102895. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102896. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102897. });
  102898. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102899. if (this._options.sizeAuto) {
  102900. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102901. this._scene.activeCamera.upperRadiusLimit) {
  102902. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102903. skyboxSize = groundSize;
  102904. }
  102905. var sceneDiagonalLenght = sceneDiagonal.length();
  102906. if (sceneDiagonalLenght > groundSize) {
  102907. groundSize = sceneDiagonalLenght * 2;
  102908. skyboxSize = groundSize;
  102909. }
  102910. // 10 % bigger.
  102911. groundSize *= 1.1;
  102912. skyboxSize *= 1.5;
  102913. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102914. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102915. }
  102916. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102917. };
  102918. /**
  102919. * Setup the ground according to the specified options.
  102920. */
  102921. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102922. var _this = this;
  102923. if (!this._ground || this._ground.isDisposed()) {
  102924. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102925. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102926. this._ground.parent = this._rootMesh;
  102927. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102928. }
  102929. this._ground.receiveShadows = this._options.enableGroundShadow;
  102930. };
  102931. /**
  102932. * Setup the ground material according to the specified options.
  102933. */
  102934. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102935. if (!this._groundMaterial) {
  102936. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102937. }
  102938. this._groundMaterial.alpha = this._options.groundOpacity;
  102939. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102940. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102941. this._groundMaterial.primaryColor = this._options.groundColor;
  102942. this._groundMaterial.useRGBColor = false;
  102943. this._groundMaterial.enableNoise = true;
  102944. if (this._ground) {
  102945. this._ground.material = this._groundMaterial;
  102946. }
  102947. };
  102948. /**
  102949. * Setup the ground diffuse texture according to the specified options.
  102950. */
  102951. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102952. if (!this._groundMaterial) {
  102953. return;
  102954. }
  102955. if (this._groundTexture) {
  102956. return;
  102957. }
  102958. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102959. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102960. return;
  102961. }
  102962. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102963. diffuseTexture.gammaSpace = false;
  102964. diffuseTexture.hasAlpha = true;
  102965. this._groundMaterial.diffuseTexture = diffuseTexture;
  102966. };
  102967. /**
  102968. * Setup the ground mirror texture according to the specified options.
  102969. */
  102970. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102971. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102972. if (!this._groundMirror) {
  102973. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102974. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102975. this._groundMirror.anisotropicFilteringLevel = 1;
  102976. this._groundMirror.wrapU = wrapping;
  102977. this._groundMirror.wrapV = wrapping;
  102978. this._groundMirror.gammaSpace = false;
  102979. if (this._groundMirror.renderList) {
  102980. for (var i = 0; i < this._scene.meshes.length; i++) {
  102981. var mesh = this._scene.meshes[i];
  102982. if (mesh !== this._ground &&
  102983. mesh !== this._skybox &&
  102984. mesh !== this._rootMesh) {
  102985. this._groundMirror.renderList.push(mesh);
  102986. }
  102987. }
  102988. }
  102989. }
  102990. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102991. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102992. };
  102993. /**
  102994. * Setup the ground to receive the mirror texture.
  102995. */
  102996. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102997. if (this._groundMaterial) {
  102998. this._groundMaterial.reflectionTexture = this._groundMirror;
  102999. this._groundMaterial.reflectionFresnel = true;
  103000. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103001. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103002. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103003. }
  103004. };
  103005. /**
  103006. * Setup the skybox according to the specified options.
  103007. */
  103008. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103009. var _this = this;
  103010. if (!this._skybox || this._skybox.isDisposed()) {
  103011. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103012. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103013. }
  103014. this._skybox.parent = this._rootMesh;
  103015. };
  103016. /**
  103017. * Setup the skybox material according to the specified options.
  103018. */
  103019. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103020. if (!this._skybox) {
  103021. return;
  103022. }
  103023. if (!this._skyboxMaterial) {
  103024. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103025. }
  103026. this._skyboxMaterial.useRGBColor = false;
  103027. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103028. this._skyboxMaterial.enableNoise = true;
  103029. this._skybox.material = this._skyboxMaterial;
  103030. };
  103031. /**
  103032. * Setup the skybox reflection texture according to the specified options.
  103033. */
  103034. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103035. if (!this._skyboxMaterial) {
  103036. return;
  103037. }
  103038. if (this._skyboxTexture) {
  103039. return;
  103040. }
  103041. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103042. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103043. return;
  103044. }
  103045. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103046. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103047. this._skyboxTexture.gammaSpace = false;
  103048. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103049. };
  103050. /**
  103051. * Dispose all the elements created by the Helper.
  103052. */
  103053. EnvironmentHelper.prototype.dispose = function () {
  103054. if (this._groundMaterial) {
  103055. this._groundMaterial.dispose(true, true);
  103056. }
  103057. if (this._skyboxMaterial) {
  103058. this._skyboxMaterial.dispose(true, true);
  103059. }
  103060. this._rootMesh.dispose(false);
  103061. };
  103062. /**
  103063. * Default ground texture URL.
  103064. */
  103065. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103066. /**
  103067. * Default skybox texture URL.
  103068. */
  103069. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103070. /**
  103071. * Default environment texture URL.
  103072. */
  103073. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103074. return EnvironmentHelper;
  103075. }());
  103076. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103077. })(BABYLON || (BABYLON = {}));
  103078. //# sourceMappingURL=babylon.environmentHelper.js.map
  103079. var BABYLON;
  103080. (function (BABYLON) {
  103081. /** Internal class used to store shapes for emitters */
  103082. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103083. function ParticleSystemSetEmitterCreationOptions() {
  103084. }
  103085. return ParticleSystemSetEmitterCreationOptions;
  103086. }());
  103087. /**
  103088. * Represents a set of particle systems working together to create a specific effect
  103089. */
  103090. var ParticleSystemSet = /** @class */ (function () {
  103091. function ParticleSystemSet() {
  103092. /**
  103093. * Gets the particle system list
  103094. */
  103095. this.systems = new Array();
  103096. }
  103097. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103098. /**
  103099. * Gets the emitter node used with this set
  103100. */
  103101. get: function () {
  103102. return this._emitterNode;
  103103. },
  103104. enumerable: true,
  103105. configurable: true
  103106. });
  103107. /**
  103108. * Creates a new emitter mesh as a sphere
  103109. * @param options defines the options used to create the sphere
  103110. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103111. * @param scene defines the hosting scene
  103112. */
  103113. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103114. if (this._emitterNode) {
  103115. this._emitterNode.dispose();
  103116. }
  103117. this._emitterCreationOptions = {
  103118. kind: "Sphere",
  103119. options: options,
  103120. renderingGroupId: renderingGroupId
  103121. };
  103122. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103123. emitterMesh.renderingGroupId = renderingGroupId;
  103124. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103125. material.emissiveColor = options.color;
  103126. emitterMesh.material = material;
  103127. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103128. var system = _a[_i];
  103129. system.emitter = emitterMesh;
  103130. }
  103131. this._emitterNode = emitterMesh;
  103132. };
  103133. /**
  103134. * Starts all particle systems of the set
  103135. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103136. */
  103137. ParticleSystemSet.prototype.start = function (emitter) {
  103138. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103139. var system = _a[_i];
  103140. if (emitter) {
  103141. system.emitter = emitter;
  103142. }
  103143. system.start();
  103144. }
  103145. };
  103146. /**
  103147. * Release all associated resources
  103148. */
  103149. ParticleSystemSet.prototype.dispose = function () {
  103150. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103151. var system = _a[_i];
  103152. system.dispose();
  103153. }
  103154. this.systems = [];
  103155. if (this._emitterNode) {
  103156. this._emitterNode.dispose();
  103157. this._emitterNode = null;
  103158. }
  103159. };
  103160. /**
  103161. * Serialize the set into a JSON compatible object
  103162. * @returns a JSON compatible representation of the set
  103163. */
  103164. ParticleSystemSet.prototype.serialize = function () {
  103165. var result = {};
  103166. result.systems = [];
  103167. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103168. var system = _a[_i];
  103169. result.systems.push(system.serialize());
  103170. }
  103171. if (this._emitterNode) {
  103172. result.emitter = this._emitterCreationOptions;
  103173. }
  103174. return result;
  103175. };
  103176. /**
  103177. * Parse a new ParticleSystemSet from a serialized source
  103178. * @param data defines a JSON compatible representation of the set
  103179. * @param scene defines the hosting scene
  103180. * @param gpu defines if we want GPU particles or CPU particles
  103181. * @returns a new ParticleSystemSet
  103182. */
  103183. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103184. if (gpu === void 0) { gpu = false; }
  103185. var result = new ParticleSystemSet();
  103186. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103187. scene = scene || BABYLON.Engine.LastCreatedScene;
  103188. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103189. var system = _a[_i];
  103190. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103191. }
  103192. if (data.emitter) {
  103193. var options = data.emitter.options;
  103194. switch (data.emitter.kind) {
  103195. case "Sphere":
  103196. result.setEmitterAsSphere({
  103197. diameter: options.diameter,
  103198. segments: options.segments,
  103199. color: BABYLON.Color3.FromArray(options.color)
  103200. }, data.emitter.renderingGroupId, scene);
  103201. break;
  103202. }
  103203. }
  103204. return result;
  103205. };
  103206. return ParticleSystemSet;
  103207. }());
  103208. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103209. })(BABYLON || (BABYLON = {}));
  103210. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103211. var BABYLON;
  103212. (function (BABYLON) {
  103213. /**
  103214. * This class is made for on one-liner static method to help creating particle system set.
  103215. */
  103216. var ParticleHelper = /** @class */ (function () {
  103217. function ParticleHelper() {
  103218. }
  103219. /**
  103220. * This is the main static method (one-liner) of this helper to create different particle systems
  103221. * @param type This string represents the type to the particle system to create
  103222. * @param scene The scene where the particle system should live
  103223. * @param gpu If the system will use gpu
  103224. * @returns the ParticleSystemSet created
  103225. */
  103226. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103227. if (gpu === void 0) { gpu = false; }
  103228. if (!scene) {
  103229. scene = BABYLON.Engine.LastCreatedScene;
  103230. ;
  103231. }
  103232. var token = {};
  103233. scene._addPendingData(token);
  103234. return new Promise(function (resolve, reject) {
  103235. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103236. scene._removePendingData(token);
  103237. return reject("Particle system with GPU is not supported.");
  103238. }
  103239. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103240. scene._removePendingData(token);
  103241. var newData = JSON.parse(data.toString());
  103242. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103243. }, undefined, undefined, undefined, function (req, exception) {
  103244. scene._removePendingData(token);
  103245. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103246. });
  103247. });
  103248. };
  103249. /**
  103250. * Static function used to export a particle system to a ParticleSystemSet variable.
  103251. * Please note that the emitter shape is not exported
  103252. * @param system defines the particle systems to export
  103253. */
  103254. ParticleHelper.ExportSet = function (systems) {
  103255. var set = new BABYLON.ParticleSystemSet();
  103256. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103257. var system = systems_1[_i];
  103258. set.systems.push(system);
  103259. }
  103260. return set;
  103261. };
  103262. /**
  103263. * Gets or sets base Assets URL
  103264. */
  103265. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103266. return ParticleHelper;
  103267. }());
  103268. BABYLON.ParticleHelper = ParticleHelper;
  103269. })(BABYLON || (BABYLON = {}));
  103270. //# sourceMappingURL=babylon.particleHelper.js.map
  103271. var BABYLON;
  103272. (function (BABYLON) {
  103273. /**
  103274. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103275. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103276. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103277. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103278. */
  103279. var VideoDome = /** @class */ (function (_super) {
  103280. __extends(VideoDome, _super);
  103281. /**
  103282. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103283. * @param name Element's name, child elements will append suffixes for their own names.
  103284. * @param urlsOrVideo defines the url(s) or the video element to use
  103285. * @param options An object containing optional or exposed sub element properties
  103286. */
  103287. function VideoDome(name, urlsOrVideo, options, scene) {
  103288. var _this = _super.call(this, name, scene) || this;
  103289. _this._useDirectMapping = false;
  103290. // set defaults and manage values
  103291. name = name || "videoDome";
  103292. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103293. options.clickToPlay = Boolean(options.clickToPlay);
  103294. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103295. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103296. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103297. if (options.useDirectMapping === undefined) {
  103298. _this._useDirectMapping = true;
  103299. }
  103300. else {
  103301. _this._useDirectMapping = options.useDirectMapping;
  103302. }
  103303. // create
  103304. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103305. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103306. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103307. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103308. // configure material
  103309. material.useEquirectangularFOV = true;
  103310. material.fovMultiplier = 1.0;
  103311. material.opacityFresnel = false;
  103312. if (_this._useDirectMapping) {
  103313. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103314. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103315. material.diffuseTexture = texture;
  103316. }
  103317. else {
  103318. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103319. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103320. material.reflectionTexture = texture;
  103321. }
  103322. // configure mesh
  103323. _this._mesh.material = material;
  103324. _this._mesh.parent = _this;
  103325. // optional configuration
  103326. if (options.clickToPlay) {
  103327. scene.onPointerUp = function () {
  103328. _this._videoTexture.video.play();
  103329. };
  103330. }
  103331. return _this;
  103332. }
  103333. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103334. /**
  103335. * Gets the video texture being displayed on the sphere
  103336. */
  103337. get: function () {
  103338. return this._videoTexture;
  103339. },
  103340. enumerable: true,
  103341. configurable: true
  103342. });
  103343. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103344. /**
  103345. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103346. * Also see the options.resolution property.
  103347. */
  103348. get: function () {
  103349. return this._material.fovMultiplier;
  103350. },
  103351. set: function (value) {
  103352. this._material.fovMultiplier = value;
  103353. },
  103354. enumerable: true,
  103355. configurable: true
  103356. });
  103357. /**
  103358. * Releases resources associated with this node.
  103359. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103360. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103361. */
  103362. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103363. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103364. this._videoTexture.dispose();
  103365. this._mesh.dispose();
  103366. this._material.dispose();
  103367. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103368. };
  103369. return VideoDome;
  103370. }(BABYLON.Node));
  103371. BABYLON.VideoDome = VideoDome;
  103372. })(BABYLON || (BABYLON = {}));
  103373. //# sourceMappingURL=babylon.videoDome.js.map
  103374. var BABYLON;
  103375. (function (BABYLON) {
  103376. /**
  103377. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103378. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103379. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103380. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103381. */
  103382. var PhotoDome = /** @class */ (function (_super) {
  103383. __extends(PhotoDome, _super);
  103384. /**
  103385. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103386. * @param name Element's name, child elements will append suffixes for their own names.
  103387. * @param urlsOfPhoto define the url of the photo to display
  103388. * @param options An object containing optional or exposed sub element properties
  103389. */
  103390. function PhotoDome(name, urlOfPhoto, options, scene) {
  103391. var _this = _super.call(this, name, scene) || this;
  103392. _this._useDirectMapping = false;
  103393. // set defaults and manage values
  103394. name = name || "photoDome";
  103395. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103396. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103397. if (options.useDirectMapping === undefined) {
  103398. _this._useDirectMapping = true;
  103399. }
  103400. else {
  103401. _this._useDirectMapping = options.useDirectMapping;
  103402. }
  103403. // create
  103404. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103405. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103406. // configure material
  103407. material.opacityFresnel = false;
  103408. material.useEquirectangularFOV = true;
  103409. material.fovMultiplier = 1.0;
  103410. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103411. // configure mesh
  103412. _this._mesh.material = material;
  103413. _this._mesh.parent = _this;
  103414. return _this;
  103415. }
  103416. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103417. /**
  103418. * Gets or sets the texture being displayed on the sphere
  103419. */
  103420. get: function () {
  103421. return this._photoTexture;
  103422. },
  103423. set: function (value) {
  103424. if (this._photoTexture === value) {
  103425. return;
  103426. }
  103427. this._photoTexture = value;
  103428. if (this._useDirectMapping) {
  103429. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103430. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103431. this._material.diffuseTexture = this._photoTexture;
  103432. }
  103433. else {
  103434. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103435. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103436. this._material.reflectionTexture = this._photoTexture;
  103437. }
  103438. },
  103439. enumerable: true,
  103440. configurable: true
  103441. });
  103442. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103443. /**
  103444. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103445. * Also see the options.resolution property.
  103446. */
  103447. get: function () {
  103448. return this._material.fovMultiplier;
  103449. },
  103450. set: function (value) {
  103451. this._material.fovMultiplier = value;
  103452. },
  103453. enumerable: true,
  103454. configurable: true
  103455. });
  103456. /**
  103457. * Releases resources associated with this node.
  103458. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103459. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103460. */
  103461. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103462. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103463. this._photoTexture.dispose();
  103464. this._mesh.dispose();
  103465. this._material.dispose();
  103466. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103467. };
  103468. return PhotoDome;
  103469. }(BABYLON.Node));
  103470. BABYLON.PhotoDome = PhotoDome;
  103471. })(BABYLON || (BABYLON = {}));
  103472. //# sourceMappingURL=babylon.photoDome.js.map
  103473. var BABYLON;
  103474. (function (BABYLON) {
  103475. BABYLON.Engine.prototype.createQuery = function () {
  103476. return this._gl.createQuery();
  103477. };
  103478. BABYLON.Engine.prototype.deleteQuery = function (query) {
  103479. this._gl.deleteQuery(query);
  103480. return this;
  103481. };
  103482. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  103483. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  103484. };
  103485. BABYLON.Engine.prototype.getQueryResult = function (query) {
  103486. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  103487. };
  103488. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  103489. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103490. this._gl.beginQuery(glAlgorithm, query);
  103491. return this;
  103492. };
  103493. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  103494. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103495. this._gl.endQuery(glAlgorithm);
  103496. return this;
  103497. };
  103498. BABYLON.Engine.prototype._createTimeQuery = function () {
  103499. var timerQuery = this.getCaps().timerQuery;
  103500. if (timerQuery.createQueryEXT) {
  103501. return timerQuery.createQueryEXT();
  103502. }
  103503. return this.createQuery();
  103504. };
  103505. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  103506. var timerQuery = this.getCaps().timerQuery;
  103507. if (timerQuery.deleteQueryEXT) {
  103508. timerQuery.deleteQueryEXT(query);
  103509. return;
  103510. }
  103511. this.deleteQuery(query);
  103512. };
  103513. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  103514. var timerQuery = this.getCaps().timerQuery;
  103515. if (timerQuery.getQueryObjectEXT) {
  103516. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  103517. }
  103518. return this.getQueryResult(query);
  103519. };
  103520. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  103521. var timerQuery = this.getCaps().timerQuery;
  103522. if (timerQuery.getQueryObjectEXT) {
  103523. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  103524. }
  103525. return this.isQueryResultAvailable(query);
  103526. };
  103527. BABYLON.Engine.prototype.startTimeQuery = function () {
  103528. var caps = this.getCaps();
  103529. var timerQuery = caps.timerQuery;
  103530. if (!timerQuery) {
  103531. return null;
  103532. }
  103533. var token = new BABYLON._TimeToken();
  103534. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103535. if (caps.canUseTimestampForTimerQuery) {
  103536. token._startTimeQuery = this._createTimeQuery();
  103537. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  103538. }
  103539. else {
  103540. if (this._currentNonTimestampToken) {
  103541. return this._currentNonTimestampToken;
  103542. }
  103543. token._timeElapsedQuery = this._createTimeQuery();
  103544. if (timerQuery.beginQueryEXT) {
  103545. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103546. }
  103547. else {
  103548. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103549. }
  103550. this._currentNonTimestampToken = token;
  103551. }
  103552. return token;
  103553. };
  103554. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  103555. var caps = this.getCaps();
  103556. var timerQuery = caps.timerQuery;
  103557. if (!timerQuery || !token) {
  103558. return -1;
  103559. }
  103560. if (caps.canUseTimestampForTimerQuery) {
  103561. if (!token._startTimeQuery) {
  103562. return -1;
  103563. }
  103564. if (!token._endTimeQuery) {
  103565. token._endTimeQuery = this._createTimeQuery();
  103566. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  103567. }
  103568. }
  103569. else if (!token._timeElapsedQueryEnded) {
  103570. if (!token._timeElapsedQuery) {
  103571. return -1;
  103572. }
  103573. if (timerQuery.endQueryEXT) {
  103574. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  103575. }
  103576. else {
  103577. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  103578. }
  103579. token._timeElapsedQueryEnded = true;
  103580. }
  103581. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103582. var available = false;
  103583. if (token._endTimeQuery) {
  103584. available = this._getTimeQueryAvailability(token._endTimeQuery);
  103585. }
  103586. else if (token._timeElapsedQuery) {
  103587. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  103588. }
  103589. if (available && !disjoint) {
  103590. var result = 0;
  103591. if (caps.canUseTimestampForTimerQuery) {
  103592. if (!token._startTimeQuery || !token._endTimeQuery) {
  103593. return -1;
  103594. }
  103595. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  103596. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  103597. result = timeEnd - timeStart;
  103598. this._deleteTimeQuery(token._startTimeQuery);
  103599. this._deleteTimeQuery(token._endTimeQuery);
  103600. token._startTimeQuery = null;
  103601. token._endTimeQuery = null;
  103602. }
  103603. else {
  103604. if (!token._timeElapsedQuery) {
  103605. return -1;
  103606. }
  103607. result = this._getTimeQueryResult(token._timeElapsedQuery);
  103608. this._deleteTimeQuery(token._timeElapsedQuery);
  103609. token._timeElapsedQuery = null;
  103610. token._timeElapsedQueryEnded = false;
  103611. this._currentNonTimestampToken = null;
  103612. }
  103613. return result;
  103614. }
  103615. return -1;
  103616. };
  103617. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  103618. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  103619. };
  103620. // We also need to update AbstractMesh as there is a portion of the code there
  103621. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  103622. var engine = this.getEngine();
  103623. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  103624. this._isOccluded = false;
  103625. return;
  103626. }
  103627. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  103628. this._isOccluded = false;
  103629. return;
  103630. }
  103631. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  103632. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  103633. if (isOcclusionQueryAvailable) {
  103634. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  103635. this._isOcclusionQueryInProgress = false;
  103636. this._occlusionInternalRetryCounter = 0;
  103637. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  103638. }
  103639. else {
  103640. this._occlusionInternalRetryCounter++;
  103641. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  103642. this._isOcclusionQueryInProgress = false;
  103643. this._occlusionInternalRetryCounter = 0;
  103644. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  103645. // if strict continue the last state of the object.
  103646. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  103647. }
  103648. else {
  103649. return;
  103650. }
  103651. }
  103652. }
  103653. var scene = this.getScene();
  103654. if (scene.getBoundingBoxRenderer) {
  103655. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  103656. if (!this._occlusionQuery) {
  103657. this._occlusionQuery = engine.createQuery();
  103658. }
  103659. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  103660. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  103661. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  103662. this._isOcclusionQueryInProgress = true;
  103663. }
  103664. };
  103665. })(BABYLON || (BABYLON = {}));
  103666. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  103667. 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}","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 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;\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","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  103668. 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);
  103669. globalObject["BABYLON"] = BABYLON;
  103670. 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 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 GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;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 StringDictionary = BABYLON.StringDictionary;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 SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;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 TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;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 Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;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 Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  103671. 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,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,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,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,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,EnvironmentTextureTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,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,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };